-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmiddleware.go
66 lines (54 loc) · 2.16 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
package jsonrpc
import (
"encoding/json"
"fmt"
"github.com/neptulon/neptulon"
)
// MiddlewareHandler defines the middleware registrar functions for a middleware stack.
type MiddlewareHandler interface {
ReqMiddleware(reqMiddleware ...func(ctx *ReqCtx) error)
NotMiddleware(notMiddleware ...func(ctx *NotCtx) error)
ResMiddleware(resMiddleware ...func(ctx *ResCtx) error)
}
// Middleware is a Neptulon middleware for handling JSON-RPC protocol and relevant JSON-RPC middleware.
type Middleware struct {
reqMiddleware []func(ctx *ReqCtx) error
notMiddleware []func(ctx *NotCtx) error
resMiddleware []func(ctx *ResCtx) error
}
// ReqMiddleware registers middleware to handle request messages.
func (mw *Middleware) ReqMiddleware(reqMiddleware ...func(ctx *ReqCtx) error) {
mw.reqMiddleware = append(mw.reqMiddleware, reqMiddleware...)
}
// NotMiddleware registers middleware to handle notification messages.
func (mw *Middleware) NotMiddleware(notMiddleware ...func(ctx *NotCtx) error) {
mw.notMiddleware = append(mw.notMiddleware, notMiddleware...)
}
// ResMiddleware registers middleware to handle response messages.
func (mw *Middleware) ResMiddleware(resMiddleware ...func(ctx *ResCtx) error) {
mw.resMiddleware = append(mw.resMiddleware, resMiddleware...)
}
// NeptulonMiddleware handles raw messages,
// categorizes the messages as one of the three JSON-RPC message types (if they are so),
// and triggers relevant middleware.
func (mw *Middleware) neptulonMiddleware(ctx *neptulon.Ctx) error {
var m message
if err := json.Unmarshal(ctx.Msg, &m); err != nil {
return fmt.Errorf("cannot deserialize message: %v", err)
}
// if the message is a request or response
if m.ID != "" {
// if the message is a request
if m.Method != "" {
return newReqCtx(m.ID, m.Method, m.Params, ctx.Client, mw.reqMiddleware, ctx.Session()).Next()
}
// if the message is a response
return newResCtx(m.ID, m.Result, ctx.Client, mw.resMiddleware, ctx.Session()).Next()
}
// if the message is a notification
if m.Method != "" {
return newNotCtx(m.Method, m.Params, ctx.Client, mw.notMiddleware, ctx.Session()).Next()
}
// not a JSON-RPC message so do nothing
return ctx.Next()
}