github.com/weaveworks/common@v0.0.0-20230728070032-dd9e68f319d5/middleware/middleware.go (about) 1 package middleware 2 3 import ( 4 "net/http" 5 ) 6 7 // Interface is the shared contract for all middlesware, and allows middlesware 8 // to wrap handlers. 9 type Interface interface { 10 Wrap(http.Handler) http.Handler 11 } 12 13 // Func is to Interface as http.HandlerFunc is to http.Handler 14 type Func func(http.Handler) http.Handler 15 16 // Wrap implements Interface 17 func (m Func) Wrap(next http.Handler) http.Handler { 18 return m(next) 19 } 20 21 // Identity is an Interface which doesn't do anything. 22 var Identity Interface = Func(func(h http.Handler) http.Handler { return h }) 23 24 // Merge produces a middleware that applies multiple middlesware in turn; 25 // ie Merge(f,g,h).Wrap(handler) == f.Wrap(g.Wrap(h.Wrap(handler))) 26 func Merge(middlesware ...Interface) Interface { 27 return Func(func(next http.Handler) http.Handler { 28 for i := len(middlesware) - 1; i >= 0; i-- { 29 next = middlesware[i].Wrap(next) 30 } 31 return next 32 }) 33 }