我的服务器中有一个非常简单的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数据?我的编码有问题吗?
答案 0 :(得分:4)
通过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..."}