WriteHTTPError is the default error response formatter.
(w http.ResponseWriter, r *http.Request, e HTTPError)
| 892 | |
| 893 | // WriteHTTPError is the default error response formatter. |
| 894 | func WriteHTTPError(w http.ResponseWriter, r *http.Request, e HTTPError) { |
| 895 | // Don't write a response if we've hit a cancellation/abort. |
| 896 | if r.Context().Err() != nil || errors.Is(e.Err, http.ErrAbortHandler) { |
| 897 | return |
| 898 | } |
| 899 | |
| 900 | // Default headers set by http.Error. |
| 901 | h := w.Header() |
| 902 | h.Set("Content-Type", "text/plain; charset=utf-8") |
| 903 | h.Set("X-Content-Type-Options", "nosniff") |
| 904 | |
| 905 | // Custom headers from the error. |
| 906 | maps.Copy(h, e.Header) |
| 907 | |
| 908 | // Write the msg back to the user. |
| 909 | w.WriteHeader(e.Code) |
| 910 | fmt.Fprint(w, e.Msg) |
| 911 | |
| 912 | // If it's a plaintext message, add line breaks and RequestID. |
| 913 | if strings.HasPrefix(h.Get("Content-Type"), "text/plain") { |
| 914 | io.WriteString(w, "\n") |
| 915 | if id := RequestIDFromContext(r.Context()); id != "" { |
| 916 | io.WriteString(w, id.String()) |
| 917 | io.WriteString(w, "\n") |
| 918 | } |
| 919 | } |
| 920 | } |
| 921 | |
| 922 | // HTTPError is an error with embedded HTTP response information. |
| 923 | // |
no test coverage detected
searching dependent graphs…