dongqiao8421 2015-02-21 10:14
浏览 38
已采纳

JSON解码器不适用于http请求正文

This question already has an answer here:

I'm starting to go crazy trying to get Go to decode this json request body. Here's a sample request:

curl -X POST -d "{\"username\":\"foo\", \"password\":\"bar\"}" http://localhost:3000/users

And here's my handler:

mux.HandleFunc("/users", func(rw http.ResponseWriter, req *http.Request) {
        var body struct {
            username string
            password string
        }

        // buf := make([]byte, req.ContentLength)
        // req.Body.Read(buf)
        // fmt.Println(string(buf))
        //
        // The above commented out code will correctly print:
        // {"username":"foo", "password":"bar"}

        err := json.NewDecoder(req.Body).Decode(&body)
        if err != nil {
            rw.WriteHeader(http.StatusNotAcceptable)
            return
        }

        fmt.Printf("%+v
", body)
        // prints -> {username: password:}
})

Like the comment suggests, I can verify that req.Body is indeed correct -- but for whatever reason, json.NewDecoder(req.Body).Decode(&body) never fills out the fields of body.

Any help would be greatly appreciated!

</div>
  • 写回答

1条回答 默认 最新

  • duanliao6077 2015-02-21 10:37
    关注

    The problem is that the json decoder does not deal with private struct fields. The fields in your body structs are private.

    Rewrite it like so and it will work:

     var body struct {
            Username string `json:"username"` 
            Password string `json:"password"`
     }
    

    basically the json:"username" is a way to tell the json decoder how to map the json name of the object to the struct name. In this instance, for decoding only, it is not necessary - the json decoder is smart enough to make the translation of the upper/lower case.

    But if you use the object to encode json as well, you need it, or you'll have upper case field names in the resulting json.

    You can use the json struct tags for a few more useful things, like omitting empty field from encoded json, or skipping fields entirely.

    You can read more about the JSON struct tags in the documentation for json.Marshal: http://golang.org/pkg/encoding/json/#Marshal

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch