关闭
dongya2578 2018-05-21 19:00
浏览 43
已采纳

为什么我的Go服务器无法正确解码从客户端发送的JSON?

I am working on writing a server in Go for a project, which involves receiving JSON data from a client and sending back a JSON response. When I run the code, any request I make works correctly, but the response is always empty. Here is the code for my server.

type AddPlayerData struct {
    name string
}

func main() {
    router := mux.NewRouter()
    router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Println("[ SUCCESS ] Request from ", r.RemoteAddr)
        decoder := json.NewDecoder(r.Body)
        var data AddPlayerData
        err := decoder.Decode(&data)
        if err != nil {
            panic(err)
        }
        defer r.Body.Close()

        json.NewEncoder(w).Encode(data)
    }).Methods("PUT");

    log.Fatal(http.ListenAndServe(":8080", router))
}

The requests I am sending are PUT requests formatted as follows:

{
    "name": "test-player"
}

I am receiving a response, but it is always empty.

  • 写回答

1条回答 默认 最新

  • dsznndq4912405 2018-05-21 19:14
    关注

    Here the issue is with you json encoding. AddPlayerData struct should export it's fields inorder for json decoder/encoder to work.

    Modify your struct to below

    type AddPlayerData struct {
        Name string `json:"name"`
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部