Render a JSON response.
(w io.Writer, v interface{})
| 117 | |
| 118 | // Render a JSON response. |
| 119 | func (j JSON) Render(w io.Writer, v interface{}) error { |
| 120 | if j.StreamingJSON { |
| 121 | return j.renderStreamingJSON(w, v) |
| 122 | } |
| 123 | |
| 124 | var buf bytes.Buffer |
| 125 | encoder := j.Encoder(&buf) |
| 126 | encoder.SetEscapeHTML(!j.UnEscapeHTML) |
| 127 | |
| 128 | if j.Indent { |
| 129 | encoder.SetIndent("", " ") |
| 130 | } |
| 131 | |
| 132 | if err := encoder.Encode(v); err != nil { |
| 133 | return err |
| 134 | } |
| 135 | |
| 136 | output := buf.Bytes() |
| 137 | |
| 138 | // JSON marshaled fine, write out the result. |
| 139 | if hw, ok := w.(http.ResponseWriter); ok { |
| 140 | j.Write(hw) |
| 141 | } |
| 142 | |
| 143 | if len(j.Prefix) > 0 { |
| 144 | _, _ = w.Write(j.Prefix) |
| 145 | } |
| 146 | |
| 147 | // Remove the newline that json.Encode injects when not indenting the output. |
| 148 | if !j.Indent { |
| 149 | output = bytes.TrimSuffix(output, []byte("\n")) |
| 150 | } |
| 151 | |
| 152 | _, _ = w.Write(output) |
| 153 | |
| 154 | return nil |
| 155 | } |
| 156 | |
| 157 | func (j JSON) renderStreamingJSON(w io.Writer, v interface{}) error { |
| 158 | if hw, ok := w.(http.ResponseWriter); ok { |
nothing calls this directly
no test coverage detected