Write outputs a standardized format to an HTTP response body. ctx is used for tracing and can be nil for tracing to be disabled. Tracing this function is helpful because JSON marshaling can sometimes take a non-insignificant amount of time, and could help us catch outliers. Additionally, we can enri
(ctx context.Context, rw http.ResponseWriter, status int, response interface{})
| 189 | // marshaling, such as the number of elements in an array, which could help us |
| 190 | // spot routes that need to be paginated. |
| 191 | func Write(ctx context.Context, rw http.ResponseWriter, status int, response interface{}) { |
| 192 | // Pretty up JSON when testing. |
| 193 | if flag.Lookup("test.v") != nil { |
| 194 | WriteIndent(ctx, rw, status, response) |
| 195 | return |
| 196 | } |
| 197 | |
| 198 | _, span := tracing.StartSpan(ctx) |
| 199 | defer span.End() |
| 200 | |
| 201 | SetAuthzCheckRecorderHeader(ctx, rw) |
| 202 | |
| 203 | rw.Header().Set("Content-Type", "application/json; charset=utf-8") |
| 204 | rw.WriteHeader(status) |
| 205 | |
| 206 | enc := json.NewEncoder(rw) |
| 207 | enc.SetEscapeHTML(true) |
| 208 | |
| 209 | // We can't really do much about these errors, it's probably due to a |
| 210 | // dropped connection. |
| 211 | _ = enc.Encode(response) |
| 212 | } |
| 213 | |
| 214 | func WriteIndent(ctx context.Context, rw http.ResponseWriter, status int, response interface{}) { |
| 215 | _, span := tracing.StartSpan(ctx) |