Ramesh S
Ramesh S

Reputation: 661

Golang proper way to send json response with status

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

Upvotes: 6

Views: 5873

Answers (2)

DAEMonRaco
DAEMonRaco

Reputation: 187

If I'm not mistaken, you can just add the status code like this:

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

Upvotes: -1

blackgreen
blackgreen

Reputation: 44608

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

Upvotes: 5

Related Questions