Documentation ¶
Index ¶
- Constants
- Variables
- func CloseNotify(next http.Handler) http.Handler
- func Compress(level int, types ...string) func(next http.Handler) http.Handler
- func DefaultCompress(next http.Handler) http.Handler
- func GetHead(next http.Handler) http.Handler
- func GetReqID(ctx context.Context) string
- func Heartbeat(endpoint string) func(http.Handler) http.Handler
- func Logger(next http.Handler) http.Handler
- func NextRequestID() uint64
- func NoCache(h http.Handler) http.Handler
- func Profiler() http.Handler
- func RealIP(h http.Handler) http.Handler
- func Recoverer(next http.Handler) http.Handler
- func RedirectSlashes(next http.Handler) http.Handler
- func RequestID(next http.Handler) http.Handler
- func RequestLogger(f LogFormatter) func(next http.Handler) http.Handler
- func StripSlashes(next http.Handler) http.Handler
- func Throttle(limit int) func(http.Handler) http.Handler
- func ThrottleBacklog(limit int, backlogLimit int, backlogTimeout time.Duration) func(http.Handler) http.Handler
- func Timeout(timeout time.Duration) func(next http.Handler) http.Handler
- func URLFormat(next http.Handler) http.Handler
- func WithLogEntry(r *http.Request, entry LogEntry) *http.Request
- func WithValue(key interface{}, val interface{}) func(next http.Handler) http.Handler
- type DefaultLogFormatter
- type LogEntry
- type LogFormatter
- type LoggerInterface
- type WrapResponseWriter
Constants ¶
const RequestIDKey ctxKeyRequestID = 0
RequestIDKey is the key that holds th unique request ID in a request context.
Variables ¶
var ( // LogEntryCtxKey is the context.Context key to store the request log entry. LogEntryCtxKey = &contextKey{"LogEntry"} // DefaultLogger is called by the Logger middleware handler to log each request. // Its made a package-level variable so that it can be reconfigured for custom // logging configurations. DefaultLogger = RequestLogger(&DefaultLogFormatter{Logger: log.New(os.Stdout, "", log.LstdFlags)}) )
var ( // URLFormatCtxKey is the context.Context key to store the URL format data // for a request. URLFormatCtxKey = &contextKey{"URLFormat"} )
Functions ¶
func CloseNotify ¶
CloseNotify is a middleware that cancels ctx when the underlying connection has gone away. It can be used to cancel long operations on the server when the client disconnects before the response is ready.
Note: this behaviour is standard in Go 1.8+, so the middleware does nothing on 1.8+ and exists just for backwards compatibility.
func Compress ¶
Compress is a middleware that compresses response body of a given content types to a data format based on Accept-Encoding request header. It uses a given compression level.
func DefaultCompress ¶
DefaultCompress is a middleware that compresses response body of predefined content types to a data format based on Accept-Encoding request header. It uses a default compression level.
func GetReqID ¶
GetReqID returns a request ID from the given context if one is present. Returns the empty string if a request ID cannot be found.
func Heartbeat ¶
Heartbeat endpoint middleware useful to setting up a path like `/ping` that load balancers or uptime testing external services can make a request before hitting any routes. It's also convenient to place this above ACL middlewares as well.
func Logger ¶
Logger is a middleware that logs the start and end of each request, along with some useful data about what was requested, what the response status was, and how long it took to return. When standard output is a TTY, Logger will print in color, otherwise it will print in black and white. Logger prints a request ID if one is provided.
Alternatively, look at https://github.com/pressly/lg and the `lg.RequestLogger` middleware pkg.
func NextRequestID ¶
func NextRequestID() uint64
NextRequestID generates the next request ID in the sequence.
func NoCache ¶
NoCache is a simple piece of middleware that sets a number of HTTP headers to prevent a router (or subrouter) from being cached by an upstream proxy and/or client.
As per http://wiki.nginx.org/HttpProxyModule - NoCache sets:
Expires: Thu, 01 Jan 1970 00:00:00 UTC Cache-Control: no-cache, private, max-age=0 X-Accel-Expires: 0 Pragma: no-cache (for HTTP/1.0 proxies/clients)
func Profiler ¶ added in v1.0.0
Profiler is a convenient subrouter used for mounting net/http/pprof. ie.
func MyService() http.Handler { r := chi.NewRouter() // ..middlewares r.Mount("/debug", middleware.Profiler()) // ..routes return r }
func RealIP ¶
RealIP is a middleware that sets a http.Request's RemoteAddr to the results of parsing either the X-Forwarded-For header or the X-Real-IP header (in that order).
This middleware should be inserted fairly early in the middleware stack to ensure that subsequent layers (e.g., request loggers) which examine the RemoteAddr will see the intended value.
You should only use this middleware if you can trust the headers passed to you (in particular, the two headers this middleware uses), for example because you have placed a reverse proxy like HAProxy or nginx in front of Goji. If your reverse proxies are configured to pass along arbitrary header values from the client, or if you use this middleware without a reverse proxy, malicious clients will be able to make you very sad (or, depending on how you're using RemoteAddr, vulnerable to an attack of some sort).
func Recoverer ¶
Recoverer is a middleware that recovers from panics, logs the panic (and a backtrace), and returns a HTTP 500 (Internal Server Error) status if possible. Recoverer prints a request ID if one is provided.
Alternatively, look at https://github.com/pressly/lg middleware pkgs.
func RedirectSlashes ¶ added in v1.0.0
RedirectSlashes is a middleware that will match request paths with a trailing slash and redirect to the same path, less the trailing slash.
func RequestID ¶
RequestID is a middleware that injects a request ID into the context of each request. A request ID is a string of the form "host.example.com/random-0001", where "random" is a base62 random string that uniquely identifies this go process, and where the last number is an atomically incremented request counter.
func RequestLogger ¶
func RequestLogger(f LogFormatter) func(next http.Handler) http.Handler
RequestLogger returns a logger handler using a custom LogFormatter.
func StripSlashes ¶ added in v1.0.0
StripSlashes is a middleware that will match request paths with a trailing slash, strip it from the path and continue routing through the mux, if a route matches, then it will serve the handler.
func Throttle ¶
Throttle is a middleware that limits number of currently processed requests at a time.
func ThrottleBacklog ¶
func ThrottleBacklog(limit int, backlogLimit int, backlogTimeout time.Duration) func(http.Handler) http.Handler
ThrottleBacklog is a middleware that limits number of currently processed requests at a time and provides a backlog for holding a finite number of pending requests.
func Timeout ¶
Timeout is a middleware that cancels ctx after a given timeout and return a 504 Gateway Timeout error to the client.
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(ctx context.Context, w http.ResponseWriter, r *http.Request) { 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 URLFormat ¶
URLFormat is a middleware that parses the url extension from a request path and stores it on the context as a string under the key `middleware.URLFormatCtxKey`. The middleware will trim the suffix from the routing path and continue routing.
Routers should not include a url parameter for the suffix when using this middleware.
Sample usage.. for url paths: `/articles/1`, `/articles/1.json` and `/articles/1.xml`
func routes() http.Handler { r := chi.NewRouter() r.Use(middleware.URLFormat) r.Get("/articles/{id}", ListArticles) return r } func ListArticles(w http.ResponseWriter, r *http.Request) { urlFormat, _ := r.Context().Value(middleware.URLFormatCtxKey).(string) switch urlFormat { case "json": render.JSON(w, r, articles) case "xml:" render.XML(w, r, articles) default: render.JSON(w, r, articles) } }
func WithLogEntry ¶
WithLogEntry sets the in-context LogEntry for a request.
Types ¶
type DefaultLogFormatter ¶
type DefaultLogFormatter struct {
Logger LoggerInterface
}
DefaultLogFormatter is a simple logger that implements a LogFormatter.
func (*DefaultLogFormatter) NewLogEntry ¶
func (l *DefaultLogFormatter) NewLogEntry(r *http.Request) LogEntry
NewLogEntry creates a new LogEntry for the request.
type LogEntry ¶
type LogEntry interface { Write(status, bytes int, elapsed time.Duration) Panic(v interface{}, stack []byte) }
LogEntry records the final log when a request completes. See defaultLogEntry for an example implementation.
func GetLogEntry ¶
GetLogEntry returns the in-context LogEntry for a request.
type LogFormatter ¶
LogFormatter initiates the beginning of a new LogEntry per request. See DefaultLogFormatter for an example implementation.
type LoggerInterface ¶
type LoggerInterface interface {
Print(v ...interface{})
}
LoggerInterface accepts printing to stdlib logger or compatible logger.
type WrapResponseWriter ¶
type WrapResponseWriter interface { http.ResponseWriter // Status returns the HTTP status of the request, or 0 if one has not // yet been sent. Status() int // BytesWritten returns the total number of bytes sent to the client. BytesWritten() int // Tee causes the response body to be written to the given io.Writer in // addition to proxying the writes through. Only one io.Writer can be // tee'd to at once: setting a second one will overwrite the first. // Writes will be sent to the proxy before being written to this // io.Writer. It is illegal for the tee'd writer to be modified // concurrently with writes. Tee(io.Writer) // Unwrap returns the original proxied target. Unwrap() http.ResponseWriter }
WrapResponseWriter is a proxy around an http.ResponseWriter that allows you to hook into various parts of the response process.
func NewWrapResponseWriter ¶
func NewWrapResponseWriter(w http.ResponseWriter, protoMajor int) WrapResponseWriter
NewWrapResponseWriter wraps an http.ResponseWriter, returning a proxy that allows you to hook into various parts of the response process.