From 8969a2f038b60b30a72a453d429e2816305244ef Mon Sep 17 00:00:00 2001 From: Tom Fenech Date: Wed, 7 Apr 2021 17:51:27 +0200 Subject: [PATCH] Add option to output unescaped HTML in JSON strings This can be useful for example when outputting a URL in a JSON value, which contains a query string, where the ampersands & should remain intact. --- responder.go | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/responder.go b/responder.go index 9365350..fda1d6a 100644 --- a/responder.go +++ b/responder.go @@ -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