英文:
Request Body is null in Go lang (Postman)
问题
我正在使用Postman在本地主机上发布JSON字符串。我在Postman中传递的JSON字符串是:
{
"name": "foo"
}
然而,当我在我的测试函数中检索数据时,我得到的req.Body
类似于这样:&{%!s(*io.LimitedReader=&{0xc0820142a0 0}) <nil> %!s(*bufio.Reader=<nil>) %!s(bool=false) %!s(bool=true) {%!s(int32=0) %!s(uint32=0)} %!s(bool=true) %!s(bool=false) %!s(bool=false)}
我希望在请求体中获取name:foo。
我用Go语言编写了相应的代码:
import (
"encoding/json"
"fmt"
"net/http"
)
type Input struct {
Name string json:"name"
}
func test(rw http.ResponseWriter, req *http.Request) {
var t Input
json.NewDecoder(req.Body).Decode(&t)
fmt.Fprintf(rw, "%s\n", req.Body)
}
func main() {
http.HandleFunc("/test", test)
http.ListenAndServe(":8080", nil)
}
有人能告诉我为什么我在req.Body属性中得到空数据吗?非常感谢。
英文:
I am using Postman to post the json string on localhost. The json string that Iam passing in Postman is :
{
“name”: "foo"
}
However, when I retrieve the data in my test function, the req.Body
i get something like this : &{%!s(*io.LimitedReader=&{0xc0820142a0 0}) <nil> %!s(*bufio.Reader=<nil>) %!s(bool=false) %!s(bool=true) {%!s(int32=0) %!s(uint32=0)} %!s(bool=true) %!s(bool=false) %!s(bool=false)}
I wish to get the name:foo in the request body.
My go lang code for the same is :
import (
"encoding/json"
"fmt"
"net/http"
)
type Input struct {
Name string `json:"name"`
}
func test(rw http.ResponseWriter, req *http.Request) {
var t Input
json.NewDecoder(req.Body).Decode(&t)
fmt.Fprintf(rw, "%s\n", req.Body)
}
func main() {
http.HandleFunc("/test", test)
http.ListenAndServe(":8080", nil)
}
Can anyone tell me why I am getting blank data in the req.Body attribute ? Thanks a lot.
答案1
得分: 1
请求体应该为空,因为你已经从中读取了所有内容。但这不是问题所在。
从你的问题来看,似乎你的输入不是有效的 JSON(你使用了“而不是")。
Decode 方法会返回错误,你应该检查一下。
if err := json.NewDecoder(req.Body).Decode(&t); err != nil {
fmt.Println(err)
}
英文:
Reuqes Body should be empty because you already read all from it. But that not the issue.
From your question, it seem your input is not valid JSON (you have “ which is different with ").
The Decode method will return error, you should check that.
if err := json.NewDecoder(req.Body).Decode(&t); err != nil {
fmt.Println(err)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论