ApiError writes an untyped (that is, "application/json") error with the provided HTTP status code and message. ApiError does not return, but instead causes the goroutine to exit.
(ctx context.Context, w http.ResponseWriter, code int, f string, v ...interface{})
| 22 | // |
| 23 | // ApiError does not return, but instead causes the goroutine to exit. |
| 24 | func apiError(ctx context.Context, w http.ResponseWriter, code int, f string, v ...interface{}) { |
| 25 | const errheader = `Clair-Error` |
| 26 | disconnect := false |
| 27 | select { |
| 28 | case <-ctx.Done(): |
| 29 | disconnect = true |
| 30 | default: |
| 31 | } |
| 32 | if ev := zlog.Debug(ctx); ev.Enabled() { |
| 33 | ev. |
| 34 | Bool("disconnect", disconnect). |
| 35 | Int("code", code). |
| 36 | Str("error", fmt.Sprintf(f, v...)). |
| 37 | Msg("http error response") |
| 38 | } else { |
| 39 | ev.Send() |
| 40 | } |
| 41 | if disconnect { |
| 42 | // Exit immediately if there's no client to read the response, anyway. |
| 43 | w.WriteHeader(statusClientClosedRequest) |
| 44 | panic(http.ErrAbortHandler) |
| 45 | } |
| 46 | |
| 47 | h := w.Header() |
| 48 | h.Del("link") |
| 49 | h.Set("content-type", "application/json") |
| 50 | h.Set("x-content-type-options", "nosniff") |
| 51 | h.Set("trailer", errheader) |
| 52 | w.WriteHeader(code) |
| 53 | |
| 54 | var buf bytes.Buffer |
| 55 | buf.WriteString(`{"code":"`) |
| 56 | switch code { |
| 57 | case http.StatusBadRequest: |
| 58 | buf.WriteString("bad-request") |
| 59 | case http.StatusMethodNotAllowed: |
| 60 | buf.WriteString("method-not-allowed") |
| 61 | case http.StatusNotFound: |
| 62 | buf.WriteString("not-found") |
| 63 | case http.StatusTooManyRequests: |
| 64 | buf.WriteString("too-many-requests") |
| 65 | default: |
| 66 | buf.WriteString("internal-error") |
| 67 | } |
| 68 | buf.WriteByte('"') |
| 69 | if f != "" { |
| 70 | buf.WriteString(`,"message":`) |
| 71 | b, _ := json.Marshal(fmt.Sprintf(f, v...)) // OK use of encoding/json. |
| 72 | buf.Write(b) |
| 73 | } |
| 74 | buf.WriteByte('}') |
| 75 | |
| 76 | if _, err := buf.WriteTo(w); err != nil { |
| 77 | h.Set(errheader, err.Error()) |
| 78 | } |
| 79 | switch err := http.NewResponseController(w).Flush(); { |
| 80 | case errors.Is(err, nil): |
| 81 | case errors.Is(err, http.ErrNotSupported): |