dongya2578 2018-05-22 03: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-22 03: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"`
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog