Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a simple JSON response

Tags:

json

go

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.

like image 594
Harry Blue Avatar asked Oct 21 '25 12:10

Harry Blue


2 Answers

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"})
like image 75
Flimzy Avatar answered Oct 23 '25 03:10

Flimzy


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)
like image 23
Edenshaw Avatar answered Oct 23 '25 03:10

Edenshaw



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!