Golang正确的方式来发送JSON响应状态

ryevplcw  于 2023-11-14  发布在  Go
关注(0)|答案(2)|浏览(160)

如何发送json响应,并在响应体中包含状态码。

我的密码

  1. func getUser(w http.ResponseWriter, r *http.Request) {
  2. w.Header().Set("Content-Type", "application/json")
  3. var user []User
  4. result := db.Find(&user)
  5. json.NewEncoder(w).Encode(result)
  6. }

字符串

我现在的结果:

  1. [
  2. {
  3. "name" : "test",
  4. "age" : "28",
  5. "email":"[email protected]"
  6. },
  7. {
  8. "name" : "sss",
  9. "age" : "60",
  10. "email":"[email protected]"
  11. },
  12. {
  13. "name" : "ddd",
  14. "age" : "30",
  15. "email":"[email protected]"
  16. },
  17. ]


但是我需要像这样发送带有status代码的响应

  1. {
  2. status : "success",
  3. statusCode : 200,
  4. data : [
  5. {
  6. "name" : "test",
  7. "age" : "28",
  8. "email":"[email protected]"
  9. },
  10. {
  11. "name" : "sss",
  12. "age" : "60",
  13. "email":"[email protected]"
  14. },
  15. {
  16. "name" : "ddd",
  17. "age" : "30",
  18. "email":"[email protected]"
  19. },
  20. ]
  21. }

hivapdat

hivapdat1#

如果你想要不同的json,传递一个不同的对象给Encode

  1. type Response struct {
  2. Status string `json:"status"`
  3. StatucCode int `json:"statusCode"`
  4. Data []User `json:"data"`
  5. }
  6. func getUser(w http.ResponseWriter, r *http.Request) {
  7. w.Header().Set("Content-Type", "application/json")
  8. var user []User
  9. result := db.Find(&user)
  10. json.NewEncoder(w).Encode(&Response{"success", 200, result})
  11. }

字符串
或者使用map

  1. json.NewEncoder(w).Encode(map[string]interface{}{
  2. "status": "success",
  3. "statusCode": 200,
  4. "data": result,
  5. })

展开查看全部
3yhwsihp

3yhwsihp2#

如果我没有弄错的话,你可以像这样添加状态码:

  1. func getUser(w http.ResponseWriter, r *http.Request) {
  2. w.Header().Set("Content-Type", "application/json")
  3. var user []User
  4. result := db.Find(&user)
  5. w.WriteHeader(http.StatusOK) // adding a status 200
  6. json.NewEncoder(w).Encode(result)
  7. }

字符串

相关问题