To return a JSON response from an HTTP server in Go, you can use the encoding/json package to marshal your data into a JSON string, and then write that string to the response body using the http.ResponseWriter interface.
Here's an example:
main.go568 chars27 linesIn this example, we define a MyData struct with two fields (Name and Age) that we want to serialize as JSON. Inside the HTTP handler function, we create an instance of this struct and marshal it into a JSON byte slice using json.Marshal(). We set the Content-Type header to application/json using ResponseWriter.Header() and then write the JSON bytes to the response body using ResponseWriter.Write().
gistlibby LogSnag