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 ansys fluent计算闪退
  • ¥15 有关wireshark抓包的问题
  • ¥15 需要写计算过程,不要写代码,求解答,数据都在图上
  • ¥15 向数据表用newid方式插入GUID问题
  • ¥15 multisim电路设计
  • ¥20 用keil,写代码解决两个问题,用库函数
  • ¥50 ID中开关量采样信号通道、以及程序流程的设计
  • ¥15 U-Mamba/nnunetv2固定随机数种子
  • ¥15 vba使用jmail发送邮件正文里面怎么加图片
  • ¥15 vb6.0如何向数据库中添加自动生成的字段数据。