github.com/hellobchain/third_party@v0.0.0-20230331131523-deb0478a2e52/go-chi/chi/chain.go (about) 1 package chi 2 3 import "github.com/hellobchain/newcryptosm/http" 4 5 // Chain returns a Middlewares type from a slice of middleware handlers. 6 func Chain(middlewares ...func(http.Handler) http.Handler) Middlewares { 7 return Middlewares(middlewares) 8 } 9 10 // Handler builds and returns a http.Handler from the chain of middlewares, 11 // with `h http.Handler` as the final handler. 12 func (mws Middlewares) Handler(h http.Handler) http.Handler { 13 return &ChainHandler{mws, h, chain(mws, h)} 14 } 15 16 // HandlerFunc builds and returns a http.Handler from the chain of middlewares, 17 // with `h http.Handler` as the final handler. 18 func (mws Middlewares) HandlerFunc(h http.HandlerFunc) http.Handler { 19 return &ChainHandler{mws, h, chain(mws, h)} 20 } 21 22 // ChainHandler is a http.Handler with support for handler composition and 23 // execution. 24 type ChainHandler struct { 25 Middlewares Middlewares 26 Endpoint http.Handler 27 chain http.Handler 28 } 29 30 func (c *ChainHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { 31 c.chain.ServeHTTP(w, r) 32 } 33 34 // chain builds a http.Handler composed of an inline middleware stack and endpoint 35 // handler in the order they are passed. 36 func chain(middlewares []func(http.Handler) http.Handler, endpoint http.Handler) http.Handler { 37 // Return ahead of time if there aren't any middlewares for the chain 38 if len(middlewares) == 0 { 39 return endpoint 40 } 41 42 // Wrap the end handler with the middleware chain 43 h := middlewares[len(middlewares)-1](endpoint) 44 for i := len(middlewares) - 2; i >= 0; i-- { 45 h = middlewares[i](h) 46 } 47 48 return h 49 }