Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 15 additions & 4 deletions responder.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,12 +88,23 @@ func HTML(w http.ResponseWriter, r *http.Request, v string) {
w.Write([]byte(v))
}

// JSON marshals 'v' to JSON, automatically escaping HTML and setting the
// Content-Type as application/json.
func JSON(w http.ResponseWriter, r *http.Request, v interface{}) {
// JSONEncoderOpt is a function that can set options on the JSON encoder.
type JSONEncoderOpt func(*json.Encoder)

// UnescapedHTML disables escaping of &, < and > in JSON strings.
func UnescapedHTML(enc *json.Encoder) {
enc.SetEscapeHTML(false)
}

// JSON marshals 'v' to JSON, automatically escaping HTML by default,
// and setting the Content-Type as application/json.
func JSON(w http.ResponseWriter, r *http.Request, v interface{}, opts ...JSONEncoderOpt) {
buf := &bytes.Buffer{}
enc := json.NewEncoder(buf)
enc.SetEscapeHTML(true)
for _, opt := range opts {
opt(enc)
}

if err := enc.Encode(v); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
Expand Down