middleware

package
v0.12.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 24, 2020 License: MIT Imports: 12 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AttachLogger

func AttachLogger(log zerolog.Logger) func(http.Handler) http.Handler

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

func CORS(appEnv string, origins ...string) func(http.Handler) http.Handler

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

func Recoverer(env string) func(http.Handler) http.Handler

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

func Timeout(timeout time.Duration) func(next http.Handler) http.Handler

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

func TrackRequest() func(http.Handler) http.Handler

TrackRequest updates a future log entry with the request parameters such as request ID and headers.

func TrackResponse

func TrackResponse() func(http.Handler) http.Handler

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
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL