JSON encode returning blank Golang [closed]

情到浓时终转凉″ 提交于 2020-01-15 06:08:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!