英文:
Handling JSON Post request in Go - error
问题
我的客户端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) {
// 从请求体中解析出用户名和密码
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');
// 清除任何错误消息。
this.set('errorMessage', null);
$.post('/api/auth.json', data).then(function(response){
// 检查响应中的令牌
self.set('errorMessage', response.message);
if(response.success){
self.set('token', response.token);
}
});
}
});
英文:
My client side javascript posts this JSON to the server side:
{ username: 'hello', password: 'world' }
My Go server side code:
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)
}
...
}
My terminal looks like the following:
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()
...
Obviously there is something wrong with the parsing of my JSON and I'm getting an error and panic(err) is being called.
The invalid character 'u' is coming from the username part in my JSON.
I've tested the client side with a Node server and it works great.
Very new to Go. Any help would be great.
Edited:
I added,
log.Println(r)
And I am getting this additional information:
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>}
Here is 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]
Full client side:
<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);
}
});
}
});
答案1
得分: 7
你需要将JSON的键值也用引号括起来,就像这样:
{ "username": "hello", "password": "world" }
严格的JSON规定键是字符串值,你可以在这里阅读规范:http://www.json.org/
英文:
You'll want to wrap the key values of your JSON with quotes as well like so:
{ "username": "hello", "password": "world" }
Strict JSON dictates that keys are string values, you can read about the spec here: http://www.json.org/
答案2
得分: 6
你没有以JSON格式发送数据。这就是为什么你的Go服务器无法读取它。使用类似这样的代码:
$.ajax({
url: '/api/auth.json',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(data)
// 你可以添加回调函数,如“complete”,“success”等。
});
我必须补充一点,我不是一个jQuery专家,可能有更简便的方法。
英文:
You are not sending data in JSON. That’s why your Go server can’t read that. Use something like this:
$.ajax({
url: '/api/auth.json',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(data)
// you can add callbacks as “complete”, “success”, etc.
});
I have to add that I’m not a jQuery expert and there may be shortcuts for this.
答案3
得分: 0
当我尝试使用POSTMAN发送请求时,我遇到了同样的问题。将请求体数据类型更改为raw
,并以json
格式添加数据,然后它将正常工作,同时头部必须是application/json
。
英文:
I faced the same issue when tried to make requests via POSTMAN. Change the body data type to raw
and add data in json
format, then it will work correctly also the headers must be application/json
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论