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.
For something that simple, you can just send a string:
w.Write(`{"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"})