EncodeJSONResponse is a EncodeResponseFunc that serializes the response as a JSON object to the ResponseWriter. Many JSON-over-HTTP services can use it as a sensible default. If the response implements Headerer, the provided headers will be applied to the response. If the response implements StatusC
(_ context.Context, w http.ResponseWriter, response interface{})
| 161 | // will be applied to the response. If the response implements StatusCoder, the |
| 162 | // provided StatusCode will be used instead of 200. |
| 163 | func EncodeJSONResponse(_ context.Context, w http.ResponseWriter, response interface{}) error { |
| 164 | w.Header().Set("Content-Type", "application/json; charset=utf-8") |
| 165 | if headerer, ok := response.(Headerer); ok { |
| 166 | for k, values := range headerer.Headers() { |
| 167 | for _, v := range values { |
| 168 | w.Header().Add(k, v) |
| 169 | } |
| 170 | } |
| 171 | } |
| 172 | code := http.StatusOK |
| 173 | if sc, ok := response.(StatusCoder); ok { |
| 174 | code = sc.StatusCode() |
| 175 | } |
| 176 | w.WriteHeader(code) |
| 177 | if code == http.StatusNoContent { |
| 178 | return nil |
| 179 | } |
| 180 | return json.NewEncoder(w).Encode(response) |
| 181 | } |
| 182 | |
| 183 | // DefaultErrorEncoder writes the error to the ResponseWriter, by default a |
| 184 | // content type of text/plain, a body of the plain text of the error, and a |
nothing calls this directly
no test coverage detected
searching dependent graphs…