JSON 编码返回空白 Golang
JSON encode returning blank Golang
我的服务器中有一个非常简单的 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)
}
}
{"Uuid":"id1234657..."}
我的服务器中有一个非常简单的 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)
}
}
{"Uuid":"id1234657..."}