Documentation › JSON API › Sending JSON responses
The response.JSON() function in the internal/response package can be used to send a JSON response with a specific HTTP status code.
You can use it like this:
func (app *application) exampleHandler(w http.ResponseWriter, r *http.Request) {
data := map[string]string{"hello": "world"}
err := response.JSON(w, http.StatusOK, data)
if err != nil {
app.serverError(w, r, err)
}
}
Note that the data parameter does not have to be a map. You can pass any JSON-marshalable value – including structs, slices, or maps – as the final argument, and it will be encoded and sent as the response body.
The response.JSON() function also automatically sets a Content-Type: application/json header on the response.
If you need to include additional HTTP headers, you can use response.JSONWithHeaders() instead. This accepts an http.Header map as the final argument.
For example:
func (app *application) exampleHandler(w http.ResponseWriter, r *http.Request) {
data := map[string]string{"hello": "world"}
headers := make(http.Header)
headers.Set("X-Server", "Go")
err := response.JSONWithHeaders(w, http.StatusOK, data, headers)
if err != nil {
app.serverError(w, r, err)
}
}