middleware.go 870 B

123456789101112131415161718192021222324252627282930313233343536
  1. // Copyright 2017 Frédéric Guillot. All rights reserved.
  2. // Use of this source code is governed by the Apache 2.0
  3. // license that can be found in the LICENSE file.
  4. package middleware
  5. import (
  6. "net/http"
  7. )
  8. // Middleware represents a HTTP middleware.
  9. type Middleware func(http.Handler) http.Handler
  10. // Chain handles a list of middlewares.
  11. type Chain struct {
  12. middlewares []Middleware
  13. }
  14. // Wrap adds a HTTP handler into the chain.
  15. func (m *Chain) Wrap(h http.Handler) http.Handler {
  16. for i := range m.middlewares {
  17. h = m.middlewares[len(m.middlewares)-1-i](h)
  18. }
  19. return h
  20. }
  21. // WrapFunc adds a HTTP handler function into the chain.
  22. func (m *Chain) WrapFunc(fn http.HandlerFunc) http.Handler {
  23. return m.Wrap(fn)
  24. }
  25. // NewChain returns a new Chain.
  26. func NewChain(middlewares ...Middleware) *Chain {
  27. return &Chain{append(([]Middleware)(nil), middlewares...)}
  28. }