关闭
duang5049 2017-10-31 20:08
浏览 76
已采纳

JSON编码返回空白Golang [关闭]

I have a very simple http resonse in my server where i json encode a struct. But its sending a blank of just {}

I don't know if i am doing it wrong but i get no errors. This is my json encode:

    // Set uuid as string to user struct
    user := User{uuid: uuid.String()}
    fmt.Println(user) // check it has the uuid

    responseWriter.Header().Set("Content-Type", "application/json")
    responseWriter.WriteHeader(http.StatusCreated)

    json.NewEncoder(responseWriter).Encode(user)

On the recieving end the data has:

Content-Type application/json
Content-Length 3
STATUS HTTP/1.1 201 Created
{}

Why does it not give me the uuid data? Am i doing something wrong with my encoding?

  • 写回答

1条回答 默认 最新

  • dongxianghui3709 2017-10-31 21:00
    关注

    Export the field name by making the first character of the identifier's name a Unicode upper case letter (Unicode class "Lu").

    Try this:

    package main
    
    import (
        "encoding/json"
        "fmt"
        "log"
        "net/http"
    )
    
    type User struct {
        Uuid string
    }
    
    func handler(responseWriter http.ResponseWriter, r *http.Request) {
        user := User{Uuid: "id1234657..."} // Set uuid as string to user struct
        fmt.Println(user)                 // check it has the uuid
        responseWriter.Header().Set("Content-Type", "application/json")
        responseWriter.WriteHeader(http.StatusCreated)
        json.NewEncoder(responseWriter).Encode(user)
    }
    
    func main() {
        http.HandleFunc("/", handler)            // set router
        err := http.ListenAndServe(":9090", nil) // set listen port
        if err != nil {
            log.Fatal("ListenAndServe: ", err)
        }
    }
    

    output(http://localhost:9090/):

    {"Uuid":"id1234657..."}
    

    展开全部

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

报告相同问题?

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

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

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

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

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

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

客服 返回
顶部