-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathmiddleware.go
81 lines (65 loc) · 1.79 KB
/
middleware.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
package go2p
import (
"fmt"
"sort"
)
// MiddlewareResult represents a result returned by a middleware
// possible values are *Stop* and *Next*
type MiddlewareResult int
const (
// Stop will be returned by a middleware when the pipe execution should be stopped
Stop MiddlewareResult = iota
// Next will be returned by a middleware when the pipe execution should be continued
Next MiddlewareResult = iota
)
// MiddlewareFunc represents a middleware implementation function
type MiddlewareFunc func(peer *Peer, pipe *Pipe, msg *Message) (MiddlewareResult, error)
// Middleware represents a wrapped middleware function with
// additional information for internal usage
type Middleware struct {
execute MiddlewareFunc
name string
pos int
}
// NewMiddleware wraps the provided action into a Middleware instance
func NewMiddleware(name string, action MiddlewareFunc) *Middleware {
return &Middleware{
name: name,
execute: action,
}
}
// String returns the string representation of this instance
func (m *Middleware) String() string {
return fmt.Sprintf("%s (%d)", m.name, m.pos)
}
type middlewares []*Middleware
func newMiddlewares(actions ...*Middleware) middlewares {
result := middlewares{}
for idx, action := range actions {
action.pos = idx
result = append(result, action)
}
return result
}
func (ml middlewares) nextItems(op PipeOperation) middlewares {
result := ml.Copy()
sort.Sort(result)
if op == Receive {
sort.Sort(sort.Reverse(result))
}
return result
}
func (ml middlewares) Copy() middlewares {
result := make(middlewares, len(ml))
copy(result, ml)
return result
}
func (ml middlewares) Len() int {
return len(ml)
}
func (ml middlewares) Swap(i, j int) {
ml[i], ml[j] = ml[j], ml[i]
}
func (ml middlewares) Less(i, j int) bool {
return ml[i].pos < ml[j].pos
}