JSON 编码返回空白 Golang

Sir*_*Sir 3 json httpresponse go

我的服务器中有一个非常简单的 http 响应,我在其中对结构进行了 json 编码。但它发送的只是一个空白{}

我不知道我是否做错了,但我没有错误。这是我的 json 编码:

    // 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)
Run Code Online (Sandbox Code Playgroud)

在接收端,数据有:

Content-Type application/json
Content-Length 3
STATUS HTTP/1.1 201 Created
{}
Run Code Online (Sandbox Code Playgroud)

为什么它不给我 uuid 数据?我的编码有问题吗?

was*_*mup 9

通过将标识符名称的第一个字符设为 Unicode 大写字母(Unicode 类“Lu”)来导出字段名称。

尝试这个:

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)
    }
}
Run Code Online (Sandbox Code Playgroud)

输出(http://localhost:9090/):

{"Uuid":"id1234657..."}
Run Code Online (Sandbox Code Playgroud)