duang5049
2017-11-01 04:08 阅读 56

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 dongxianghui3709 2017-11-01 05: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..."}
    
    点赞 评论 复制链接分享

相关推荐