-
Notifications
You must be signed in to change notification settings - Fork 6
/
claw.go
113 lines (99 loc) · 2.32 KB
/
claw.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
/**********************************
*** Middleware Chaining in Go ***
*** Code is under MIT license ***
*** Code by CodingFerret ***
*** github.com/squiidz ***
***********************************/
package claw
import (
"net/http"
)
// CalwHandler only wrap a http.Handler
type ClawHandler struct {
http.Handler
}
// newHandler Generate a pointer to a ClawHandler
func newHandler(h http.Handler) *ClawHandler {
return &ClawHandler{h}
}
// ClawFunc redefine http.HandlerFunc
type ClawFunc func(rw http.ResponseWriter, req *http.Request)
// Serve HTTP Request
func (c ClawFunc) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
c(rw, req)
}
// Middleware is the signature of a valid middleware with Claw
type MiddleWare func(http.Handler) http.Handler
// Claw is the array of the Global Middleware
type Claw struct {
Handlers []MiddleWare
}
// New create a new empty Claw
func New(m ...interface{}) *Claw {
c := &Claw{}
if m != nil {
c.Handlers = toMiddleware(m...)
}
return c
}
// Use, merge all the global middleware with the provided http.HandlerFunc
func (c *Claw) Use(h http.HandlerFunc) *ClawHandler {
if len(c.Handlers) > 0 {
var stack ClawHandler
for i, m := range c.Handlers {
switch i {
case 0:
stack = *newHandler(m(h))
default:
stack = *newHandler(m(stack))
}
}
return &stack
}
return newHandler(ClawFunc(h))
}
// Merge all the global middleware with the provided http.HandlerFunc
func (c *Claw) Merge(h http.Handler) *ClawHandler {
if len(c.Handlers) > 0 {
var stack ClawHandler
for i, m := range c.Handlers {
switch i {
case 0:
stack = *newHandler(m(h))
default:
stack = *newHandler(m(stack))
}
}
return &stack
}
return newHandler(h)
}
// Add some middleware to a particular handler
func (c *ClawHandler) Add(m ...interface{}) *ClawHandler {
var n http.Handler
if m != nil {
stack := toMiddleware(m...)
for i, s := range stack {
if i == 0 {
n = s(c)
} else {
n = s(n)
}
}
}
return newHandler(n)
}
// Stack takes a Stack type variable and use it on the ClawHandler who call the function.
func (c *ClawHandler) Stack(stk ...Stack) *ClawHandler {
var t http.Handler
for _, s := range stk {
for i, _ := range s {
if i == 0 {
t = s[(len(s)-1)-i](c)
} else {
t = s[(len(s)-1)-i](t)
}
}
}
return newHandler(t)
}