Home > Software design >  Golang proper way to send json response with status
Golang proper way to send json response with status

Time:10-01

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":"[email protected]"
    },
    {
        "name" : "sss",
        "age" : "60",
        "email":"[email protected]"
    },
    {
        "name" : "ddd",
        "age" : "30",
        "email":"[email protected]"
    },
]

But I need to send the response with status code like this

{
    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]"
        },
    ]
}

CodePudding user response:

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,
})
  • Related