-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.go
More file actions
51 lines (42 loc) · 1.51 KB
/
middleware.go
File metadata and controls
51 lines (42 loc) · 1.51 KB
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
package middleware
import (
"net/http"
)
// Middleware - A function type for defining middleware
type Middleware func(http.HandlerFunc) http.HandlerFunc
// Decorator - Interface for defining a middleware wrapping mechanism. This
// interface exists for the purpose of testing, but, of course, can be used
// at your discretion.
type Decorator interface {
// Append - Add Middleware to the beginning of the decorator chain. This
// Middleware will wrap all existing middleware.
Append(Middleware) Decorator
// Prepend - Add Middleware to the end of the decorator chain. This Middleware
// will be wrapped by all existing Middleware.
Prepend(Middleware) Decorator
// WrapHandler - Wraps the http.HandlerFunc with the Middleware added via the
// Append and Prepend methods
WrapHandler(http.HandlerFunc) http.HandlerFunc
}
// Wrapper - Concrete implementation of the Decorator interface
type Wrapper struct {
middlewares []Middleware
}
// Append - Concrete implementation of the Decorator.Append method
func (w *Wrapper) Append(mw Middleware) Decorator {
w.middlewares = append([]Middleware{mw}, w.middlewares...)
return w
}
// Prepend - Concrete implementation of the Decorator.Prepend method
func (w *Wrapper) Prepend(m Middleware) Decorator {
w.middlewares = append(w.middlewares, m)
return w
}
// WrapHandler - Concrete implementation of the Decorator.WrapHandler method
func (w *Wrapper) WrapHandler(h http.HandlerFunc) http.HandlerFunc {
var mw Middleware
for _, mw = range w.middlewares {
h = mw(h)
}
return h
}