JSON 编码返回空白 Golang

标签 json go httpresponse

<分区>

我的服务器中有一个非常简单的 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)

在接收端数据有:

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

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

最佳答案

通过the first character of the identifier's name a Unicode upper case letter (Unicode class "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)
    }
}

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

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

关于JSON 编码返回空白 Golang,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47048073/

相关文章:

Java servlet - 从子页面转发/重定向

javascript - JSON,语法错误 : unexpected token I(. ..)

java - 将 hibernate 实体转换为 JSON : oblectId instead of whole object

go - 如何使用GCP在pubsub模型中一次向所有订阅者发送消息

go - 处理超时并收听 channel

go - 使 httputil.ReverseProxy 转发响应流正确

c# - 从 MVC 3 JsonResult 获取美化的 JSON

java - 使用Rxjava作为EventBus时如何从事件中获取参数

mongodb - 如何检索 []bson.M 类型的 map

Delphi:Indy - 如何获得错误的响应体?