如何发送状态码的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":"test@gmail.com"
},
{
"name" : "sss",
"age" : "60",
"email":"ss@gmail.com"
},
{
"name" : "ddd",
"age" : "30",
"email":"ddd@gmail.com"
},
]
但是我需要像这样用status
代码发送响应
{
status : "success",
statusCode : 200,
data : [
{
"name" : "test",
"age" : "28",
"email":"test@gmail.com"
},
{
"name" : "sss",
"age" : "60",
"email":"ss@gmail.com"
},
{
"name" : "ddd",
"age" : "30",
"email":"ddd@gmail.com"
},
]
}
如果你想要不同的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,
})