Movatterモバイル変換


[0]ホーム

URL:


Warning Deprecated: Please upgrade to the latest major version: go get github.com/go-chi/chi/v5
Notice  The highest tagged major version isv5.

middleware

package
v1.5.5Latest Latest
Warning

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

Go to latest
Published: Sep 7, 2023 License:MITImports:27Imported by:5,243

Details

Repository

github.com/go-chi/chi

Links

Documentation

Index

Constants

View Source
const RequestIDKey ctxKeyRequestID = 0

RequestIDKey is the key that holds the unique request ID in a request context.

Variables

View Source
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(nexthttp.Handler)http.Handler)
View Source
var RequestIDHeader = "X-Request-Id"

RequestIDHeader is the name of the HTTP Header which contains the request id.Exported so that it can be changed by developers

View Source
var (// URLFormatCtxKey is the context.Context key to store the URL format data// for a request.URLFormatCtxKey = &contextKey{"URLFormat"})

Functions

funcAllowContentEncodingadded inv1.5.0

func AllowContentEncoding(contentEncoding ...string) func(nexthttp.Handler)http.Handler

AllowContentEncoding enforces a whitelist of request Content-Encoding otherwise respondswith a 415 Unsupported Media Type status.

funcAllowContentTypeadded inv1.5.0

func AllowContentType(contentTypes ...string) func(nexthttp.Handler)http.Handler

AllowContentType enforces a whitelist of request Content-Types otherwise respondswith a 415 Unsupported Media Type status.

funcBasicAuthadded inv1.5.0

func BasicAuth(realmstring, creds map[string]string) func(nexthttp.Handler)http.Handler

BasicAuth implements a simple middleware handler for adding basic http auth to a route.

funcCleanPathadded inv1.5.1

func CleanPath(nexthttp.Handler)http.Handler

CleanPath middleware will clean out double slash mistakes from a user's request path.For example, if a user requests /users//1 or //users////1 will both be treated as: /users/1

funcCompress

func Compress(levelint, types ...string) func(nexthttp.Handler)http.Handler

Compress is a middleware that compresses responsebody of a given content types to a data format basedon Accept-Encoding request header. It uses a givencompression level.

NOTE: make sure to set the Content-Type header on your responseotherwise this middleware will not compress the response body. For ex, inyour handler you should set w.Header().Set("Content-Type", http.DetectContentType(yourBody))or set it manually.

Passing a compression level of 5 is sensible value

funcContentCharsetadded inv1.5.0

func ContentCharset(charsets ...string) func(nexthttp.Handler)http.Handler

ContentCharset generates a handler that writes a 415 Unsupported Media Type response if none of the charsets match.An empty charset will allow requests with no Content-Type header or no specified charset.

funcGetHeadadded inv1.5.0

func GetHead(nexthttp.Handler)http.Handler

GetHead automatically route undefined HEAD requests to GET handlers.

funcGetReqID

func GetReqID(ctxcontext.Context)string

GetReqID returns a request ID from the given context if one is present.Returns the empty string if a request ID cannot be found.

funcHeartbeatadded inv1.5.0

func Heartbeat(endpointstring) func(http.Handler)http.Handler

Heartbeat endpoint middleware useful to setting up a path like`/ping` that load balancers or uptime testing external servicescan make a request before hitting any routes. It's also convenientto place this above ACL middlewares as well.

funcLogger

func Logger(nexthttp.Handler)http.Handler

Logger is a middleware that logs the start and end of each request, alongwith 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 willprint in color, otherwise it will print in black and white. Logger prints arequest ID if one is provided.

Alternatively, look athttps://github.com/goware/httplog for a more in-depthhttp logger with structured logging support.

IMPORTANT NOTE: Logger should go before any other middleware that may changethe response, such as `middleware.Recoverer`. Example:

```gor := chi.NewRouter()r.Use(middleware.Logger) // <--<< Logger should come before Recovererr.Use(middleware.Recoverer)r.Get("/", handler)```

funcNewadded inv1.5.0

func New(hhttp.Handler) func(nexthttp.Handler)http.Handler

New will create a new middleware handler from a http.Handler.

funcNextRequestIDadded inv1.5.0

func NextRequestID()uint64

NextRequestID generates the next request ID in the sequence.

funcNoCache

func NoCache(hhttp.Handler)http.Handler

NoCache is a simple piece of middleware that sets a number of HTTP headers to preventa router (or subrouter) from being cached by an upstream proxy and/or client.

As perhttp://wiki.nginx.org/HttpProxyModule - NoCache sets:

Expires: Thu, 01 Jan 1970 00:00:00 UTCCache-Control: no-cache, private, max-age=0X-Accel-Expires: 0Pragma: no-cache (for HTTP/1.0 proxies/clients)

funcPrintPrettyStackadded inv1.5.0

func PrintPrettyStack(rvr interface{})

funcProfileradded inv1.0.0

func Profiler()http.Handler

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}

funcRealIP

func RealIP(hhttp.Handler)http.Handler

RealIP is a middleware that sets a http.Request's RemoteAddr to the resultsof parsing either the X-Forwarded-For header or the X-Real-IP header (in thatorder).

This middleware should be inserted fairly early in the middleware stack toensure that subsequent layers (e.g., request loggers) which examine theRemoteAddr will see the intended value.

You should only use this middleware if you can trust the headers passed toyou (in particular, the two headers this middleware uses), for examplebecause you have placed a reverse proxy like HAProxy or nginx in front ofchi. If your reverse proxies are configured to pass along arbitrary headervalues from the client, or if you use this middleware without a reverseproxy, malicious clients will be able to make you very sad (or, depending onhow you're using RemoteAddr, vulnerable to an attack of some sort).

funcRecoverer

func Recoverer(nexthttp.Handler)http.Handler

Recoverer is a middleware that recovers from panics, logs the panic (and abacktrace), and returns a HTTP 500 (Internal Server Error) status ifpossible. Recoverer prints a request ID if one is provided.

Alternatively, look athttps://github.com/pressly/lg middleware pkgs.

funcRedirectSlashesadded inv1.0.0

func RedirectSlashes(nexthttp.Handler)http.Handler

RedirectSlashes is a middleware that will match request paths with a trailingslash and redirect to the same path, less the trailing slash.

NOTE: RedirectSlashes middleware is *incompatible* with http.FileServer,seehttps://github.com/go-chi/chi/issues/343

funcRequestID

func RequestID(nexthttp.Handler)http.Handler

RequestID is a middleware that injects a request ID into the context of eachrequest. 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 goprocess, and where the last number is an atomically incremented requestcounter.

funcRequestLoggeradded inv1.5.0

func RequestLogger(fLogFormatter) func(nexthttp.Handler)http.Handler

RequestLogger returns a logger handler using a custom LogFormatter.

funcSetHeaderadded inv1.5.0

func SetHeader(key, valuestring) func(nexthttp.Handler)http.Handler

SetHeader is a convenience handler to set a response header key/value

funcStripSlashesadded inv1.0.0

func StripSlashes(nexthttp.Handler)http.Handler

StripSlashes is a middleware that will match request paths with a trailingslash, strip it from the path and continue routing through the mux, if a routematches, then it will serve the handler.

funcThrottle

func Throttle(limitint) func(http.Handler)http.Handler

Throttle is a middleware that limits number of currently processed requestsat a time across all users. Note: Throttle is not a rate-limiter per user,instead it just puts a ceiling on the number of currentl in-flight requestsbeing processed from the point from where the Throttle middleware is mounted.

funcThrottleBacklog

func ThrottleBacklog(limit, backlogLimitint, backlogTimeouttime.Duration) func(http.Handler)http.Handler

ThrottleBacklog is a middleware that limits number of currently processedrequests at a time and provides a backlog for holding a finite number ofpending requests.

funcThrottleWithOptsadded inv1.5.0

func ThrottleWithOpts(optsThrottleOpts) func(http.Handler)http.Handler

ThrottleWithOpts is a middleware that limits number of currently processed requests using passed ThrottleOpts.

funcTimeout

func Timeout(timeouttime.Duration) func(nexthttp.Handler)http.Handler

Timeout is a middleware that cancels ctx after a given timeout and returna 504 Gateway Timeout error to the client.

It's required that you select the ctx.Done() channel to check for the signalif the context has reached its deadline and return, otherwise the timeoutsignal 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")) })

funcURLFormatadded inv1.5.0

func URLFormat(nexthttp.Handler)http.Handler

URLFormat is a middleware that parses the url extension from a request path and stores iton the context as a string under the key `middleware.URLFormatCtxKey`. The middleware willtrim 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)  }}

funcWithLogEntryadded inv1.5.0

func WithLogEntry(r *http.Request, entryLogEntry) *http.Request

WithLogEntry sets the in-context LogEntry for a request.

funcWithValueadded inv1.5.0

func WithValue(key, val interface{}) func(nexthttp.Handler)http.Handler

WithValue is a middleware that sets a given key/value in a context chain.

Types

typeCompressoradded inv1.5.0

type Compressor struct {// contains filtered or unexported fields}

Compressor represents a set of encoding configurations.

funcNewCompressoradded inv1.5.0

func NewCompressor(levelint, types ...string) *Compressor

NewCompressor creates a new Compressor that will handle encoding responses.

The level should be one of the ones defined in the flate package.The types are the content types that are allowed to be compressed.

func (*Compressor)Handleradded inv1.5.0

func (c *Compressor) Handler(nexthttp.Handler)http.Handler

Handler returns a new middleware that will compress the response based on thecurrent Compressor.

func (*Compressor)SetEncoderadded inv1.5.0

func (c *Compressor) SetEncoder(encodingstring, fnEncoderFunc)

SetEncoder can be used to set the implementation of a compression algorithm.

The encoding should be a standardised identifier. See:https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Encoding

For example, add the Brotli algortithm:

import brotli_enc "gopkg.in/kothar/brotli-go.v0/enc"compressor := middleware.NewCompressor(5, "text/html")compressor.SetEncoder("br", func(w http.ResponseWriter, level int) io.Writer {  params := brotli_enc.NewBrotliParams()  params.SetQuality(level)  return brotli_enc.NewBrotliWriter(params, w)})

typeDefaultLogFormatteradded inv1.5.0

type DefaultLogFormatter struct {LoggerLoggerInterfaceNoColorbool}

DefaultLogFormatter is a simple logger that implements a LogFormatter.

func (*DefaultLogFormatter)NewLogEntryadded inv1.5.0

func (l *DefaultLogFormatter) NewLogEntry(r *http.Request)LogEntry

NewLogEntry creates a new LogEntry for the request.

typeEncoderFuncadded inv1.5.0

type EncoderFunc func(wio.Writer, levelint)io.Writer

An EncoderFunc is a function that wraps the provided io.Writer with astreaming compression algorithm and returns it.

In case of failure, the function should return nil.

typeHeaderRouteadded inv1.5.0

type HeaderRoute struct {MatchAny   []PatternMatchOnePatternMiddleware func(nexthttp.Handler)http.Handler}

func (HeaderRoute)IsMatchadded inv1.5.0

func (rHeaderRoute) IsMatch(valuestring)bool

typeHeaderRouteradded inv1.5.0

type HeaderRouter map[string][]HeaderRoute

funcRouteHeadersadded inv1.5.0

func RouteHeaders()HeaderRouter

RouteHeaders is a neat little header-based router that allows you to directthe flow of a request through a middleware stack based on a request header.

For example, lets say you'd like to setup multiple routers depending on therequest Host header, you could then do something as so:

r := chi.NewRouter()rSubdomain := chi.NewRouter()

r.Use(middleware.RouteHeaders().

Route("Host", "example.com", middleware.New(r)).Route("Host", "*.example.com", middleware.New(rSubdomain)).Handler)

r.Get("/", h)rSubdomain.Get("/", h2)

Another example, imagine you want to setup multiple CORS handlers, where foryour origin servers you allow authorized requests, but for third-party publicrequests, authorization is disabled.

r := chi.NewRouter()

r.Use(middleware.RouteHeaders().

  Route("Origin", "https://app.skyweaver.net", cors.Handler(cors.Options{   AllowedOrigins:   []string{"https://api.skyweaver.net"},   AllowedMethods:   []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},   AllowedHeaders:   []string{"Accept", "Authorization", "Content-Type"},   AllowCredentials: true, // <----------<<< allow credentials  })).  Route("Origin", "*", cors.Handler(cors.Options{   AllowedOrigins:   []string{"*"},   AllowedMethods:   []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},   AllowedHeaders:   []string{"Accept", "Content-Type"},   AllowCredentials: false, // <----------<<< do not allow credentials  })).  Handler)

func (HeaderRouter)Handleradded inv1.5.0

func (hrHeaderRouter) Handler(nexthttp.Handler)http.Handler

func (HeaderRouter)Routeadded inv1.5.0

func (hrHeaderRouter) Route(header, matchstring, middlewareHandler func(nexthttp.Handler)http.Handler)HeaderRouter

func (HeaderRouter)RouteAnyadded inv1.5.0

func (hrHeaderRouter) RouteAny(headerstring, match []string, middlewareHandler func(nexthttp.Handler)http.Handler)HeaderRouter

func (HeaderRouter)RouteDefaultadded inv1.5.0

func (hrHeaderRouter) RouteDefault(handler func(nexthttp.Handler)http.Handler)HeaderRouter

typeLogEntryadded inv1.5.0

type LogEntry interface {Write(status, bytesint, headerhttp.Header, elapsedtime.Duration, extra interface{})Panic(v interface{}, stack []byte)}

LogEntry records the final log when a request completes.See defaultLogEntry for an example implementation.

funcGetLogEntryadded inv1.5.0

func GetLogEntry(r *http.Request)LogEntry

GetLogEntry returns the in-context LogEntry for a request.

typeLogFormatteradded inv1.5.0

type LogFormatter interface {NewLogEntry(r *http.Request)LogEntry}

LogFormatter initiates the beginning of a new LogEntry per request.See DefaultLogFormatter for an example implementation.

typeLoggerInterfaceadded inv1.5.0

type LoggerInterface interface {Print(v ...interface{})}

LoggerInterface accepts printing to stdlib logger or compatible logger.

typePatternadded inv1.5.0

type Pattern struct {// contains filtered or unexported fields}

funcNewPatternadded inv1.5.0

func NewPattern(valuestring)Pattern

func (Pattern)Matchadded inv1.5.0

func (pPattern) Match(vstring)bool

typeThrottleOptsadded inv1.5.0

type ThrottleOpts struct {LimitintBacklogLimitintBacklogTimeouttime.DurationRetryAfterFn   func(ctxDonebool)time.Duration}

ThrottleOpts represents a set of throttling options.

typeWrapResponseWriteradded inv1.5.0

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 hookinto various parts of the response process.

funcNewWrapResponseWriteradded inv1.5.0

func NewWrapResponseWriter(whttp.ResponseWriter, protoMajorint)WrapResponseWriter

NewWrapResponseWriter wraps an http.ResponseWriter, returning a proxy that allows you tohook into various parts of the response process.

Source Files

View all Source files

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp