英文:
Golang proper way to send json response with status
问题
如何在响应体中发送带有状态码的json
响应。
我的代码
func getUser(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var user []User
result := db.Find(&user)
response := map[string]interface{}{
"status": "success",
"statusCode": 200,
"data": result,
}
json.NewEncoder(w).Encode(response)
}
我的当前结果:
[
{
"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"
},
]
}
英文:
How to send json
response with status code in response body.
My code
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)
}
My result now:
[
{
"name" : "test",
"age" : "28",
"email":"test@gmail.com"
},
{
"name" : "sss",
"age" : "60",
"email":"ss@gmail.com"
},
{
"name" : "ddd",
"age" : "30",
"email":"ddd@gmail.com"
},
]
But I need to send the response with status
code like this
{
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"
},
]
}
答案1
得分: 5
如果你想要不同的 JSON,可以将不同的对象传递给 Encode
方法。
type Response struct {
Status string `json:"status"`
StatusCode 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,
})
英文:
If you want different json, pass a different object to 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})
}
Or use a map
:
json.NewEncoder(w).Encode(map[string]interface{}{
"status": "success",
"statusCode": 200,
"data": result,
})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论