问题
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:
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..."}
来源:https://stackoverflow.com/questions/47048073/json-encode-returning-blank-golang