【问题标题】:Golang proper way to send json response with statusGolang正确发送带有状态的json响应的方法
【发布时间】:2021-11-22 20:56:43
【问题描述】:

如何在响应正文中发送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"
        },
    ]
}

【问题讨论】:

    标签: mysql json go select go-gorm


    【解决方案1】:

    如果您想要不同的 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,
    })
    

    【讨论】:

    • 感谢您的回答。我有一个疑问,我们应该创建struct。还有其他选择吗?
    • 现在alphabetical order 中的响应就像{"data":"Successfully Encoded","status":"success","statusCode":200}。如何设置它是默认的,就像我们给出的一样
    • @RameshS 地图未排序。如果您想要具有有序输出的 json,则必须使用 struct。你可以使用结构体字面量代替预定义结构体,但我更喜欢预定义结构体,因为它更容易理解
    猜你喜欢
    • 2022-08-16
    • 1970-01-01
    • 2021-02-02
    • 2019-10-09
    • 2016-08-17
    • 1970-01-01
    • 2011-06-28
    • 2011-10-26
    • 1970-01-01
    相关资源
    最近更新 更多