如何发送
json
响应并在响应正文中包含状态代码。
我的代码
func getUser(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var user []User
result := db.Find(&user)
json.NewEncoder(w).Encode(result)
}
我现在的成绩:
[
{
"name" : "test",
"age" : "28",
"email":"[email protected]"
},
{
"name" : "sss",
"age" : "60",
"email":"[email protected]"
},
{
"name" : "ddd",
"age" : "30",
"email":"[email protected]"
},
]
但是我需要使用这样的
status
代码发送响应
{
status : "success",
statusCode : 200,
data : [
{
"name" : "test",
"age" : "28",
"email":"[email protected]"
},
{
"name" : "sss",
"age" : "60",
"email":"[email protected]"
},
{
"name" : "ddd",
"age" : "30",
"email":"[email protected]"
},
]
}
如果您想要不同的 json,请将不同的对象传递给
Encode
。
type Response struct {
Status string `json:"status"`
StatucCode int `json:"statusCode"`
Data []User `json:"data"`
}
func getUser(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var user []User
result := db.Find(&user)
json.NewEncoder(w).Encode(&Response{"success", 200, result})
}
或者使用
map
:
json.NewEncoder(w).Encode(map[string]interface{}{
"status": "success",
"statusCode": 200,
"data": result,
})
如果我没记错的话,你可以像这样添加状态代码:
func getUser(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var user []User
result := db.Find(&user)
w.WriteHeader(http.StatusOK) // adding a status 200
json.NewEncoder(w).Encode(result)
}