httpHandlerFunc lets you write an http handler that just returns an error, which will be turned into a 500 http response if non-nil, or a specific code if the error is of type httpError. It also accepts a generic extra argument that will be passed to the handler function to support providing any ext
(fn func(http.ResponseWriter, *http.Request, T) error, t T)
| 2276 | // It also accepts a generic extra argument that will be passed to the handler function to support |
| 2277 | // providing any extra already initialized state. |
| 2278 | func httpHandlerFunc[T any](fn func(http.ResponseWriter, *http.Request, T) error, t T) http.HandlerFunc { |
| 2279 | return func(w http.ResponseWriter, r *http.Request) { |
| 2280 | err := fn(w, r, t) |
| 2281 | if err == nil { |
| 2282 | return |
| 2283 | } |
| 2284 | |
| 2285 | bklog.G(r.Context()). |
| 2286 | WithField("method", r.Method). |
| 2287 | WithField("path", r.URL.Path). |
| 2288 | WithError(err).Error("failed to serve request") |
| 2289 | |
| 2290 | // check whether this is a hijacked connection, if so we can't write any http errors to it |
| 2291 | if _, testErr := w.Write(nil); testErr == http.ErrHijacked { |
| 2292 | return |
| 2293 | } |
| 2294 | |
| 2295 | var httpErr httpError |
| 2296 | var gqlErr gqlError |
| 2297 | switch { |
| 2298 | case errors.As(err, &httpErr): |
| 2299 | httpErr.WriteTo(w) |
| 2300 | case errors.As(err, &gqlErr): |
| 2301 | gqlErr.WriteTo(w) |
| 2302 | default: |
| 2303 | http.Error(w, err.Error(), http.StatusInternalServerError) |
| 2304 | } |
| 2305 | } |
| 2306 | } |