github.com/hellofresh/janus@v0.0.0-20230925145208-ce8de8183c67/pkg/render/responder.go (about) 1 package render 2 3 import ( 4 "bytes" 5 "encoding/json" 6 "net/http" 7 ) 8 9 // M is a simple abstraction for a map interface 10 type M map[string]interface{} 11 12 // JSON marshals 'v' to JSON, automatically escaping HTML and setting the 13 // Content-Type as application/json. 14 func JSON(w http.ResponseWriter, code int, v interface{}) { 15 buf := &bytes.Buffer{} 16 enc := json.NewEncoder(buf) 17 enc.SetEscapeHTML(true) 18 if err := enc.Encode(v); err != nil { 19 http.Error(w, err.Error(), http.StatusInternalServerError) 20 return 21 } 22 23 w.Header().Set("Content-Type", "application/json") 24 w.WriteHeader(code) 25 w.Write(buf.Bytes()) 26 }