-
Notifications
You must be signed in to change notification settings - Fork 5
/
chain.go
45 lines (35 loc) · 1.04 KB
/
chain.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package chain
import (
"net/http"
)
// Constructor is the function contract used to make RequestHandlers.
type Constructor func(http.Handler) http.Handler
// Chain enables easy definition of custom handler chains.
type Chain []Constructor
// New creates a new chain with the supplied Constructors.
func New(cc ...Constructor) Chain {
return cc
}
// Handler compiles the chain to a single RequestHandler.
func (c Chain) Handler(h http.Handler) http.Handler {
l := len(c) - 1
// Execute in reverse order
for i := range c {
h = c[l-i](h)
}
return h
}
// Append adds the Constructor to the end of the execution chain.
func (c Chain) Append(cc ...Constructor) Chain {
newChain := make(Chain, 0, len(c)+len(cc))
newChain = append(newChain, c...)
newChain = append(newChain, cc...)
return newChain
}
// Prepend adds the Constructor to the start of the execution chain.
func (c Chain) Prepend(cc ...Constructor) Chain {
newChain := make(Chain, 0, len(c)+len(cc))
newChain = append(newChain, cc...)
newChain = append(newChain, c...)
return newChain
}