我的客户端 javascript 将此 JSON 发布到服务器端:
{ username: 'hello', password: 'world' }
我的 Go 服务器端代码:
type AuthJSON struct {
Username string `json:"username"`
Password string `json:"password"`
}
func AuthenticationHandler(w http.ResponseWriter, r *http.Request) {
// Parse the incoming user/pass from the request body
var body AuthJSON
err := json.NewDecoder(r.Body).Decode(&body)
log.Println(body)
log.Println(body.Username)
if err != nil {
log.Println(err)
panic(err)
}
...
}
我的终端如下所示:
2013/07/31 20:26:53 { }
2013/07/31 20:26:53
2013/07/31 20:26:53 invalid character 'u' looking for beginning of value
2013/07/31 20:26:53 http: panic serving [::1]:58141: invalid character 'u' looking for beginning of value
goroutine 9 [running]:
net/http.func·007()
...
显然,我的 JSON 解析有问题,我收到错误,并且正在调用 panic(err)。
无效字符“u”来自我的 JSON 中的用户名部分。
我已经用 Node 服务器测试了客户端,效果很好。Go 非常新。任何帮助都会很棒。
编辑:
我补充说,
log.Println(r)
我得到了这个额外的信息:
2013/07/31 20:59:47 &{POST /api/auth.json HTTP/1.1 1 1 map[Accept-Encoding:[gzip, deflate] Content-Type:[application/x-www-form-urlencoded; charset=UTF-8] X-Requested-With:[XMLHttpRequest] Content-Length:[30] Connection:[keep-alive] Pragma:[no-cache] Cache-Control:[no-cache] User-Agent:[Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:22.0) Gecko/20100101 Firefox/22.0] Accept:[*/*] Accept-Language:[en-US,en;q=0.5] Referer:[http://localhost:8080/]] 0x114adee0 30 [] false localhost:8080 map[] map[] <nil> map[] [::1]:58372 /api/auth.json <nil>}
这是 b, _ := ioutil.ReadAll(r.Body); log.Println(b)
2013/08/01 07:48:40 [117 115 101 114 110 97 109 101 61 104 101 108 108 111 38 112 97 115 115 119 111 114 100 61 119 111 114 108 100]
完整的客户端:
<script type="text/x-handlebars" data-template-name="login">
{{#if loggedIn}}
<p>You are already logged in!</p>
{{else}}
<form class="form-inline" {{action login on="submit"}}>
<h2>Log In</h2>
{{input value=username type="text" placeholder="Username"}}
{{input value=password type="password" placeholder="Password"}}
{{input class="btn" type="submit" value="Log In"}}
</form>
{{#if errorMessage}}
<div class="alert alert-error">{{errorMessage}}</div>
{{/if}}
{{/if}}
</script>
App.LoginController = Ember.Controller.extend({
login: function() {
var self = this, data = this.getProperties('username', 'password');
// Clear out any error messages.
this.set('errorMessage', null);
$.post('/api/auth.json', data).then(function(response){
// Check the response for the token
self.set('errorMessage', response.message);
if(response.success){
self.set('token', response.token);
}
});
}
});