diff --git a/respond/json.go b/respond/json.go new file mode 100755 index 0000000..39ef24b --- /dev/null +++ b/respond/json.go @@ -0,0 +1,25 @@ +package respond + +import ( + "encoding/json" + "net/http" + + "github.com/Jille/convreq/internal" +) + +type respondJSON struct { + data interface{} +} + +// Respond implements convreq.HttpResponse. +func (rj respondJSON) Respond(w http.ResponseWriter, r *http.Request) error { + if w.Header().Get("Content-Type") == "" { + w.Header().Set("Content-Type", "application/json") + } + return json.NewEncoder(w).Encode(rj.data) +} + +// ServeJSON uses json.Marshal() to serve a JSON object. +func ServeJSON(data interface{}) internal.HttpResponse { + return respondJSON{data} +}