github.com/hechain20/hechain@v0.0.0-20220316014945-b544036ba106/core/middleware/chain.go (about) 1 /* 2 Copyright hechain. All Rights Reserved. 3 4 SPDX-License-Identifier: Apache-2.0 5 */ 6 7 package middleware 8 9 import ( 10 "net/http" 11 12 "github.com/hechain20/hechain/common/flogging" 13 ) 14 15 var logger = flogging.MustGetLogger("middleware") 16 17 type Middleware func(http.Handler) http.Handler 18 19 // A Chain is a middleware chain use for http request processing. 20 type Chain struct { 21 mw []Middleware 22 } 23 24 // NewChain creates a new Middleware chain. The chain will call the Middleware 25 // in the order provided. 26 func NewChain(middlewares ...Middleware) Chain { 27 return Chain{ 28 mw: append([]Middleware{}, middlewares...), 29 } 30 } 31 32 // Handler returns an http.Handler for this chain. 33 func (c Chain) Handler(h http.Handler) http.Handler { 34 if h == nil { 35 h = http.DefaultServeMux 36 } 37 38 for i := len(c.mw) - 1; i >= 0; i-- { 39 h = c.mw[i](h) 40 } 41 return h 42 }