【发布时间】:2015-10-20 18:58:59
【问题描述】:
我正在使用 Postman 在 localhost 上发布 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 lang 代码是:
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 属性中得到空白数据?非常感谢。
【问题讨论】:
-
您应该打印
t而不是req.Body。 请:处理每一个错误。 -
@Volker:我试过了。打印 t 给我一个空白 '{}' 。里面什么都没有:(
-
你是如何打印
t的?喜欢"%s", t.name或"%#v", t。 “{}”的输出看起来很奇怪。并处理每一个错误。 -
我猜您的 JSON 解码失败并且您忽略了错误 - 您在上面发布的 JSON 看起来确实很奇怪,因为它在
name周围使用了这些“特殊”引号。因此,正如@Volker 建议的那样,首先尝试处理 所有 错误。 -
是的,处理错误是个问题。我刚刚知道错误处理在 GO 中有多么重要。谢谢大家:)
标签: json http go postman gorilla