Documentation ¶
Index ¶
- func AttachLogger(log zerolog.Logger) func(http.Handler) http.Handler
- func CORS(appEnv string, origins ...string) func(http.Handler) http.Handler
- func DefaultMiddleware(router *chi.Mux, log zerolog.Logger, conf MiddlwareConfig)
- func Recoverer(env string) func(http.Handler) http.Handler
- func Timeout(timeout time.Duration) func(next http.Handler) http.Handler
- func TrackRequest() func(http.Handler) http.Handler
- func TrackResponse() func(http.Handler) http.Handler
- type MiddlwareConfig
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AttachLogger ¶
AttachLogger attaches a new zerolog.Logger to each new HTTP request. Stolen from https://github.com/rs/zerolog/blob/master/hlog/hlog.go
func CORS ¶
CORS sets CORS for the handler based on the app environment, making the rules lax in dev environment.
func DefaultMiddleware ¶
func DefaultMiddleware(router *chi.Mux, log zerolog.Logger, conf MiddlwareConfig)
Sets a reasonable set of middleware in the right order taking into consideration those that defer computation(especially)
Middleware set up include: - RequestID - RealIP - RedirectSlashes - Compress - CORS - Request/Response Logging - Panic Recovery(with special support for APIError) - Timeout - Request logger
func Recoverer ¶
Recoverer creates a middleware that handles panics from chi controllers. It handles printing(optionally stack trace in dev env) and responding to the client for all errors except JSendErrors. Note that all errors(bar JSendError) respond with a 500
func Timeout ¶
Timeout is a middleware that cancels ctx after a given timeout and return a 504 Gateway Timeout error to the client. P.S this was copied directly from go-chi, we only removed the header writing part
It's required that you select the ctx.Done() channel to check for the signal if the context has reached its deadline and return, otherwise the timeout signal will be just ignored.
ie. a route/handler may look like:
r.Get("/long", func(w http.ResponseWriter, r *http.Request) { ctx := r.Context() processTime := time.Duration(rand.Intn(4)+1) * time.Second select { case <-ctx.Done(): return case <-time.After(processTime): // The above channel simulates some hard work. } w.Write([]byte("done")) })
func TrackRequest ¶
TrackRequest updates a future log entry with the request parameters such as request ID and headers.
Types ¶
type MiddlwareConfig ¶
type MiddlwareConfig struct { Environment string // Application environment(dev, test e.t.c.) Timeout time.Duration // Duration of request before it returns a 504. Defaults to 1 minute CompressionLevel int // Level of compression for responses. Defaults to 5 CORSOrigins []string // list of allowed origins }