-
Notifications
You must be signed in to change notification settings - Fork 0
/
context.go
68 lines (58 loc) · 1.43 KB
/
context.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
package natsby
import (
"io"
"time"
"github.com/nats-io/nats.go"
)
// Context context that's passed through handlers and middleware
type Context struct {
*nats.Msg
handlers HandlersChain
ByteReplyPayload []byte
JSONReplyPayload interface{}
didReply bool
index int8
*nats.Conn
*nats.EncodedConn
Err error
Keys map[string]interface{}
outWriter io.ReadWriter
errWriter io.ReadWriter
}
// Next to be called in middleware to invoke the middleware chain
func (c *Context) Next() {
c.index++
for c.index < int8(len(c.handlers)) {
c.handlers[c.index](c)
c.index++
}
}
// NextWithLatencyDuration Calls Next() and returns duration of execution
func (c *Context) NextWithLatencyDuration() time.Duration {
start := time.Now()
c.Next()
end := time.Now()
return end.Sub(start)
}
func (c *Context) reset() {
c.index = -1
}
// Set sets arbitrary value that will be available in the context map
func (c *Context) Set(k string, v interface{}) {
if c.Keys == nil {
c.Keys = make(map[string]interface{})
}
c.Keys[k] = v
}
// Get gets arbirary value from the context map
func (c *Context) Get(k string) interface{} {
return c.Keys[k]
}
// GetByteReplyPayload getter for byte reply payload with metadata about if it was set
func (c *Context) GetByteReplyPayload() ([]byte, bool) {
if c.didReply == false {
return []byte(""), false
}
return c.ByteReplyPayload, true
}
// TODO: GetJSONReplyPayload