Harry Blue
Harry Blue

Reputation: 4522

Returning a simple JSON response

I am currently moving an Express API over to a Golang implementation.

In Express, if I want to return a simple, ad hoc json response I can do like

app.get('/status', (req, res) => res.json({status: 'OK'}))

However, I am struggling to understand this in Go.

Do I need to create a struct for this simple response?

I was trying something like this

func getStatus(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode({status: "OK"})
}

but this is obviously not going to work.

Upvotes: 4

Views: 10059

Answers (2)

Jonathan Hall
Jonathan Hall

Reputation: 79754

For something that simple, you can just send a string:

w.Write([]byte(`{"status":"OK"}`))

But to answer your broader question, you need to define your object in Go notation. This can be as simple as:

json.NewEncoder(w).Encode(map[string]string{"status": "OK"})

Upvotes: 13

Edenshaw
Edenshaw

Reputation: 1757

Don't use Encode because it will return a base64 string, instead use this:

responseWriter.Header().Set("Content-Type", "application/json")
responseWriter.WriteHeader(http.StatusOK)
jsonData := []byte(`{"status":"OK"}`)
responseWriter.Write(jsonData)

If you want to return a base64 string, use this then:

responseWriter.Header().Set("Content-Type", "application/json")
responseWriter.WriteHeader(http.StatusOK)
jsonData := []byte(`{"status":"OK"}`)
json.NewEncoder(responseWriter).Encode(jsonData)

Upvotes: 1

Related Questions