return a json response from a http server in go

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.go
package main

import (
    "encoding/json"
    "net/http"
)

type MyData struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        data := MyData{"John", 30}
        jsonBytes, err := json.Marshal(data)
        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }
        w.Header().Set("Content-Type", "application/json")
        w.Write(jsonBytes)
    })

    http.ListenAndServe(":8080", nil)
}
568 chars
27 lines

In 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().

related categories

gistlibby LogSnag