Newer
Older
minecraft-ui / internal / rest / encode.go
Simon Lindgren on 10 Mar 2018 653 bytes first commit
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)
}