Documentation ¶
Index ¶
- Constants
- Variables
- func AllowContentEncoding(contentEncoding ...string) func(next http.Handler) http.Handler
- func AllowContentType(contentTypes ...string) func(next http.Handler) http.Handler
- func BasicAuth(realm string, creds map[string]string) func(next http.Handler) http.Handler
- func CleanPath(next http.Handler) http.Handler
- func Compress(level int, types ...string) func(next http.Handler) http.Handler
- func ContentCharset(charsets ...string) func(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 Maybe(mw func(http.Handler) http.Handler, maybeFn func(r *http.Request) bool) func(http.Handler) http.Handler
- func New(h http.Handler) func(next http.Handler) http.Handler
- func NextRequestID() uint64
- func NoCache(h http.Handler) http.Handler
- func PageRoute(path string, handler http.Handler) func(http.Handler) http.Handler
- func PathRewrite(old, new string) func(http.Handler) http.Handler
- func PrintPrettyStack(rvr interface{})
- 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 SetHeader(key, value string) 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, backlogLimit int, backlogTimeout time.Duration) func(http.Handler) http.Handler
- func ThrottleWithOpts(opts ThrottleOpts) 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, val interface{}) func(next http.Handler) http.Handler
- type Compressor
- type DefaultLogFormatter
- type EncoderFunc
- type HeaderRoute
- type HeaderRouter
- func (hr HeaderRouter) Handler(next http.Handler) http.Handler
- func (hr HeaderRouter) Route(header, match string, middlewareHandler func(next http.Handler) http.Handler) HeaderRouter
- func (hr HeaderRouter) RouteAny(header string, match []string, ...) HeaderRouter
- func (hr HeaderRouter) RouteDefault(handler func(next http.Handler) http.Handler) HeaderRouter
- type LogEntry
- type LogFormatter
- type LoggerInterface
- type Pattern
- type ThrottleOpts
- type WrapResponseWriter
Constants ¶
const RequestIDKey ctxKeyRequestID = 0
RequestIDKey is the key that holds the 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 func(next http.Handler) http.Handler )
var IsTTY bool
var (
// RequestIDHeader is the name of the HTTP Header which contains the request id.
RequestIDHeader = "X-Request-Id"
)
var URLFormatCtxKey = &contextKey{"URLFormat"}
URLFormatCtxKey is the context.Context key to store the URL format data for a request.
Functions ¶
func AllowContentEncoding ¶
AllowContentEncoding enforces the Content-Encoding whitelist of the request, otherwise it responds with a status of 415 Unsupported Media Type.
func AllowContentType ¶
AllowContentType ensures that request content types are whitelisted, otherwise it responds with a status of 415 Unsupported Media Type.
func BasicAuth ¶
BasicAuth implements a simple middleware handler for adding basic http auth to a route.
func CleanPath ¶
The CleanPath middleware will clean the user's request path from double-slash errors. For example, if a user requests /users//1 or //users////1, both requests will be treated as: /users/1
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. NOTE: Be sure to set the Content-Type header on your response, otherwise this middleware will not compress the response body. For example, you must set w.Header().Set("Content-Type", http.DetectContentType(yourBody)) in the handler or set it manually. Passing a compression level of 5 is reasonable value.
func ContentCharset ¶
ContentCharset generates a handler that writes a 415 Unsupported Media Type response if none of the charsets match. An empty charset resolves requests with no Content-Type header or no specified charset.
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 is useful for configuring a path like `/ping` so that load balancers or external health testing services can make a request before hitting any routes. It's also handy to place above intermediate ACL components.
func Logger ¶
Logger is the 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. If the standard output is TTY, Logger will print in color, otherwise it will print in black and white. Logger prints the request ID if one is provided. IMPORTANT NOTE: Logger must work before any other middleware that can change the response, such as middleware.Recoverer.
func Maybe ¶
func Maybe(mw func(http.Handler) http.Handler, maybeFn func(r *http.Request) bool) func(http.Handler) http.Handler
Maybe middleware allows you to change the execution flow of the middleware stack depending on the return value of maybeFn(request). This is useful, for example, if you want to skip the middleware handler if the request does not satisfy the logic of maybeFn.
func NextRequestID ¶
func NextRequestID() uint64
NextRequestID generates the next request ID in the sequence.
func NoCache ¶
NoCache is a simple piece of middleware that installs a series of HTTP headers to prevent the router (or subrouter) from being cached by the upstream proxy server and/or client.
func PageRoute ¶
PageRoute is a simple middleware that allows to route a static GET request at the middleware stack level.
func PathRewrite ¶
PathRewrite is a simple middleware that allows to rewrite the path of a request URL.
func PrintPrettyStack ¶
func PrintPrettyStack(rvr interface{})
func RealIP ¶
RealIP is the middleware that sets the RemoteAddr http.Request to the parsing results of the True-Client-IP, X-Real-IP or X-Forwarded-For headers (in that order). This middleware must be inserted fairly early in the middleware stack to ensure that subsequent layers (such as request loggers) that check the RemoteAddr will see the intended value. You only need to use this middleware if you can trust the passed headers, for example because you have set up a reverse proxy, such as HAProxy or nginx, before gor. If your reverse proxies are configured to pass arbitrary header values from the client, or if you use this middleware without a reverse proxy, malicious clients will be able to make vulnerable to some attack.
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.
func RedirectSlashes ¶
RedirectSlashes is a middleware that will map request paths with a slash and redirect to the same path minus the slash.
func RequestID ¶
RequestID is a middleware that injects a request ID in the context of each request. The request ID is a string of the form "host.example.com/random-0001", where "random" is a random base62 string that uniquely identifies this go process, and 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 ¶
StripSlashes is a middleware that will look for request paths with a slash at the end, remove it from the path and continue routing through the mux, if the route matches, it will serve the handler.
func Throttle ¶
Throttle is a middleware that limits the number of current requests being processed simultaneously for all users. Note: Throttle is not a rate limiter for each user, instead it simply sets a ceiling on the number of current requests processed from the point at which the Throttle middleware is installed.
func ThrottleBacklog ¶
func ThrottleBacklog(limit, backlogLimit int, backlogTimeout time.Duration) func(http.Handler) http.Handler
ThrottleBacklog is a middleware that limits the number of pending requests at a time and provides a backlog to store the final number of pending requests.
func ThrottleWithOpts ¶
func ThrottleWithOpts(opts ThrottleOpts) func(http.Handler) http.Handler
ThrottleWithOpts is a middleware that limits number of currently processed requests using passed ThrottleOpts.
func Timeout ¶
Timeout is a middleware that cancels ctx after a given timeout and returns a 504 Gateway Timeout error to the client. It's required that you select the ctx.Done() channel to check the signal if the context has reached its deadline and return, otherwise the timeout signal will be just ignored.
func URLFormat ¶
URLFormat is a middleware that parses the url extension from the request path and stores it in context as a string under the `middleware.URLFormatCtxKey`. The middleware trims the suffix from the routing path and continues routing. Routers must not include a url parameter for the suffix when using this middleware.
func WithLogEntry ¶
WithLogEntry sets the incontext LogEntry for a request.
Types ¶
type Compressor ¶
type Compressor struct {
// contains filtered or unexported fields
}
Compressor represents a set of encoding configurations.
func NewCompressor ¶
func NewCompressor(level int, types ...string) *Compressor
NewCompressor creates a new Compressor which will handle the encoding responses. The level must be one of those defined in the flate package. The types are the content types that are allowed to be compressed.
func (*Compressor) Handler ¶
func (c *Compressor) Handler(next http.Handler) http.Handler
Handler returns a new middleware that will compress the response based on the current Compressor.
func (*Compressor) SetEncoder ¶
func (c *Compressor) SetEncoder(encoding string, fn EncoderFunc)
SetEncoder can be used to set the implementation of a compression algorithm.
type DefaultLogFormatter ¶
type DefaultLogFormatter struct { Logger LoggerInterface NoColor bool }
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 EncoderFunc ¶
EncoderFunc is a function that wraps the stream compression algorithm provided by io.Writer and returns it. If it fails, the function should return nil.
type HeaderRoute ¶
type HeaderRoute struct { Middleware func(next http.Handler) http.Handler MatchOne Pattern MatchAny []Pattern }
func (HeaderRoute) IsMatch ¶
func (r HeaderRoute) IsMatch(value string) bool
type HeaderRouter ¶
type HeaderRouter map[string][]HeaderRoute
func RouteHeaders ¶
func RouteHeaders() HeaderRouter
RouteHeaders is a small header-based router that allows you to route a request flow through the middleware stack based on the request header. For example, suppose you want to configure multiple routers based on the Host request header.
func (HeaderRouter) Route ¶
func (hr HeaderRouter) Route(header, match string, middlewareHandler func(next http.Handler) http.Handler) HeaderRouter
func (HeaderRouter) RouteAny ¶
func (hr HeaderRouter) RouteAny(header string, match []string, middlewareHandler func(next http.Handler) http.Handler) HeaderRouter
func (HeaderRouter) RouteDefault ¶
func (hr HeaderRouter) RouteDefault(handler func(next http.Handler) http.Handler) HeaderRouter
type LogEntry ¶
type LogEntry interface { Write(status, bytes int, header http.Header, elapsed time.Duration, extra interface{}) Panic(v interface{}, stack []byte) }
LogEntry records the final log when a request completes.
func GetLogEntry ¶
GetLogEntry returns the in-context LogEntry for a request.
type LogFormatter ¶
LogFormatter initiates the beginning of a new LogEntry per request.
type LoggerInterface ¶
type LoggerInterface interface {
Print(v ...interface{})
}
LoggerInterface accepts printing to stdlib logger or compatible logger.
type ThrottleOpts ¶
type ThrottleOpts struct { RetryAfterFn func(ctxDone bool) time.Duration Limit int BacklogLimit int BacklogTimeout time.Duration }
ThrottleOpts represents a set of throttling options.
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 a write through it. // Only one io.Writer can be written to tee to at once: // installing a second one will overwrite the first one. // Before writing to a given io.Writer, the data will be sent to the proxy. // It is forbidden to change the proxy writer at the same time as writing. Tee(io.Writer) // Unwrap returns the original proxied target. Unwrap() http.ResponseWriter }
WrapResponseWriter is a proxy around an http.ResponseWriter that allows to hook into various parts of the response process.
func NewWrapResponseWriter ¶
func NewWrapResponseWriter(w http.ResponseWriter, protoMajor int) WrapResponseWriter
NewWrapResponseWriter wraps http.ResponseWriter, returning a proxy that allows to hook into various parts of the response process.
Source Files ¶
- basic_auth.go
- clean_path.go
- compress.go
- content_charset.go
- content_encoding.go
- content_type.go
- get_head.go
- heartbeat.go
- logger.go
- maybe.go
- middleware.go
- nocache.go
- page_route.go
- path_rewrite.go
- profiler.go
- realip.go
- recoverer.go
- request_id.go
- route_headers.go
- strip.go
- terminal.go
- throttle.go
- timeout.go
- url_format.go
- value.go
- wrap_writer.go