在Go语言中,请求体为空(Postman)

huangapple go评论115阅读模式
英文:

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)
}

huangapple
  • 本文由 发表于 2015年10月20日 18:15:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/33233942.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定