-
Notifications
You must be signed in to change notification settings - Fork 3
/
handler.go
86 lines (68 loc) · 1.69 KB
/
handler.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
package exposed
import (
"bufio"
"fmt"
"net"
"github.com/rs/zerolog"
"github.com/thesyncim/exposed/encoding"
)
// exposedCtx implements *exposedCtx
type exposedCtx struct {
Request *request
Response *response
codec encoding.Codec
}
func newExposedCtx(codec encoding.Codec) func() *exposedCtx {
return func() *exposedCtx {
return &exposedCtx{
codec: codec,
Response: AcquireResponse(),
Request: acquireRequest(),
}
}
}
func (h *exposedCtx) Handle(ctxv *exposedCtx) (rctxv *exposedCtx) {
eh := ctxv
defer func() {
if r := recover(); r != nil {
eh.Response.SwapError(append([]byte("panic captured: "), []byte(fmt.Sprint(r))...))
rctxv = ctxv
return
}
}()
handler, err := match(eh.Request.Operation())
if err != nil {
h.Response.SwapError([]byte(err.Error()))
return ctxv
}
opinfo := getOperationInfo(eh.Request.Operation())
args := opinfo.ArgsType()
if err := h.codec.Unmarshal(eh.Request.Payload(), args); err != nil {
panic(err)
}
reply := opinfo.ReplyType()
if err = handler(nil, args, reply); err != nil {
eh.Response.SwapError([]byte(err.Error()))
return ctxv
}
v, err := h.codec.Marshal(reply)
if err != nil {
eh.Response.SwapError([]byte(err.Error()))
return ctxv
}
eh.Response.SwapPayload(v)
return ctxv
}
func (h *exposedCtx) ConcurrencyLimitError(concurrency int) {
h.Response.SwapError([]byte("max concurrency exceeded"))
}
func (h *exposedCtx) Init(conn net.Conn, logger *zerolog.Logger) {
h.Request.Reset()
h.Response.Reset()
}
func (h *exposedCtx) ReadRequest(br *bufio.Reader) error {
return h.Request.ReadRequest(br)
}
func (h *exposedCtx) WriteResponse(bw *bufio.Writer) error {
return h.Response.WriteResponse(bw)
}