登录
首页 >  Golang >  Go问答

读取不了 json 正文

来源:stackoverflow

时间:2024-03-05 16:18:28 249浏览 收藏

Golang小白一枚,正在不断学习积累知识,现将学习到的知识记录一下,也是将我的所得分享给大家!而今天这篇文章《读取不了 json 正文》带大家来了解一下##content_title##,希望对大家的知识积累有所帮助,从而弥补自己的不足,助力实战开发!


问题内容

对 golang 来说相当陌生,我正在尝试读取 golang 中的 post json 请求正文,但它只是转换为空字符串。

下面是我尝试通过请求 json 正文转换为的结构

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 请求正文

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 的空字符串

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

有什么我遗漏的地方吗?我几乎搜索了所有地方,这几乎正在被使用。


解决方案


问题是 sdppost 字段未导出,因此 json 解码器看不到它们,您可以这样修复:

type SdpPost struct {
    Id string
    Sdp string
}

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>