2017-11-20 06:10:04 +01:00
|
|
|
// Copyright 2017 Frédéric Guillot. All rights reserved.
|
|
|
|
// Use of this source code is governed by the Apache 2.0
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
|
|
|
package middleware
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
)
|
|
|
|
|
2017-11-28 06:30:04 +01:00
|
|
|
// Middleware represents a HTTP middleware.
|
2017-11-20 06:10:04 +01:00
|
|
|
type Middleware func(http.Handler) http.Handler
|
|
|
|
|
2017-11-28 06:30:04 +01:00
|
|
|
// Chain handles a list of middlewares.
|
|
|
|
type Chain struct {
|
2017-11-20 06:10:04 +01:00
|
|
|
middlewares []Middleware
|
|
|
|
}
|
|
|
|
|
2017-11-28 06:30:04 +01:00
|
|
|
// Wrap adds a HTTP handler into the chain.
|
|
|
|
func (m *Chain) Wrap(h http.Handler) http.Handler {
|
2017-11-20 06:10:04 +01:00
|
|
|
for i := range m.middlewares {
|
|
|
|
h = m.middlewares[len(m.middlewares)-1-i](h)
|
|
|
|
}
|
|
|
|
|
|
|
|
return h
|
|
|
|
}
|
|
|
|
|
2017-11-28 06:30:04 +01:00
|
|
|
// WrapFunc adds a HTTP handler function into the chain.
|
|
|
|
func (m *Chain) WrapFunc(fn http.HandlerFunc) http.Handler {
|
2017-11-20 06:10:04 +01:00
|
|
|
return m.Wrap(fn)
|
|
|
|
}
|
|
|
|
|
2017-11-28 06:30:04 +01:00
|
|
|
// NewChain returns a new Chain.
|
|
|
|
func NewChain(middlewares ...Middleware) *Chain {
|
|
|
|
return &Chain{append(([]Middleware)(nil), middlewares...)}
|
2017-11-20 06:10:04 +01:00
|
|
|
}
|