dongya2578
dongya2578
2018-05-22 03:00

为什么我的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 dsznndq4912405 3年前

    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"`
    }
    
    点赞 评论 复制链接分享