This repository has been archived by the owner on Jul 9, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chain.go
58 lines (50 loc) · 1.71 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
46
47
48
49
50
51
52
53
54
55
56
57
// package fusion provides chaing for both fasthttp RequestHandler and RequestHandler based Middleware
package fusion
import (
"github.com/valyala/fasthttp"
"github.com/buaazp/fasthttprouter"
)
// type definition for Middleware that takes in a RequestHandler
type Middleware func(fasthttp.RequestHandler) fasthttp.RequestHandler
// Handlers acts as a simple function that
func Handlers(hs ...fasthttp.RequestHandler) fasthttp.RequestHandler {
return func(ctx *fasthttp.RequestCtx) {
for _, h := range hs {
if (ctx.Response.StatusCode() < 400) {
h(ctx)
}
}
}
}
// Abstraction for RequestHandler Middleware slice.
type Middlewares struct {
middlewares []Middleware
}
// New creates a new Chain with given Middlewares
// Middlewares are only called upon a call to Then().
func New(ms ...Middleware) *Middlewares {
return &Middlewares{ms}
}
// Handler chains the middlewares and returns the final http.Handler.
// New(m1, m2, m3).Handle(h)
// is equivalent to:
// m1(m2(m3(h)))
// When the request comes in, it will be passed m1 -> m2 -> m3 -> handler
// (assuming every middleware calls the following one).
//
// A chain can be safely reused by calling Handle() several times.
// stdStack := fusion.New(ratelimitHandler, csrfHandler)
// indexPipe = stdStack.Handler(indexHandler)
// authPipe = stdStack.Handler(authHandler)
// For proper middleware, this should cause no problems.
//
// Handler() treats nil as fasthttprouter.New().Handler
func (m *Middlewares) Handler(handler fasthttp.RequestHandler) fasthttp.RequestHandler {
if handler == nil {
handler = fasthttprouter.New().Handler
}
for i := range m.middlewares {
handler = m.middlewares[len(m.middlewares) - 1 - i](handler)
}
return handler
}