问题描述
golang非常陌生,我正在尝试阅读golang中的json请求正文,但它只是转换为空字符串.
Quite new to golang, I am trying to read the post json request body in golang, but it just converts to empty string.
下面是我尝试通过请求json主体转换为
Below is the struct which I am trying to convert by request json body to
type SdpPost struct {
id string
sdp string
}
func (s *SdpPost) Id() string {
return s.id
}
func (s *SdpPost) SetSdp(sdp string) {
s.sdp = sdp
}
func (s *SdpPost) Sdp() string {
return s.sdp
}
当我尝试打印以下代码段时,我确实看到了我通过邮递员传递的json请求正文
When I try to print the below snippet, I do see my json request body which I am passing through postman
Dumping the json POST /v1/sdp HTTP/1.1
Host: localhost:8080
Accept: */*
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Content-Length: 62
Content-Type: application/json
Postman-Token: 5f0f9961-f058-446a-86e8-7f047c1dc5cc
User-Agent: PostmanRuntime/7.24.1
{
"sdp":"This is the test sdp",
"id":"This is the test id"
}
但是下面的代码什么也不打印,它只是ID和sdp的空字符串
But the below code prints nothing, it is just empty string for Id and sdp
r.Header.Set("Content-Type", "application/json")
decoder := json.NewDecoder(r.Body)
sdp := handler.SdpPost{}
decoder.Decode(&sdp)
w.WriteHeader(http.StatusOK)
fmt.Print(sdp.Id())
fmt.Println(sdp.Sdp())
我在某处缺少什么吗?我从字面上搜索了所有地方,这几乎被使用了.
Is there anything which I am missing somewhere? I literally searched every where and this is pretty much being used.
推荐答案
问题是未导出 SdpPost
字段,因此json解码器看不到它们,您可以这样解决:>
Problem is that SdpPost
fields are unexported, so json decoder doesn't see them, you can fix that like that:
type SdpPost struct {
Id string
Sdp string
}
这篇关于无法读取json正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!