Respond with JSON

Let's default to sending JSON responses, for this we use package encoding/json.
import ( - "fmt" + "encoding/json" "log" "net/http" "os" @@ -24,5 +24,11 @@ func NewRouter() (router *http.ServeMux) { type books struct{} func (h *books) ServeHTTP(w http.ResponseWriter, r *http.Request) { - fmt.Fprint(w, "No books available!") + w.Header().Set("Content-Type", "application/json") + model := struct { + Message string + }{ + "No books available!", + } + json.NewEncoder(w).Encode(model) }
prev toc next