package rest import ( "net/http" "bytes" "encoding/json" "fmt" ) // JSON marshals v to JSON, automatically setting the Content-Type as // application/json and escaping HTML. func JSON(w http.ResponseWriter, r *http.Request, v interface{}) { buf := &bytes.Buffer{} enc := json.NewEncoder(buf) enc.SetEscapeHTML(true) if err := enc.Encode(v); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Set("Content-Type", ContentTypeApplicationJSON) if status, ok := r.Context().Value(StatusCtxKey).(int); ok { w.WriteHeader(status) } _, err := w.Write(buf.Bytes()) fmt.Errorf("JSON: %#v", err) }