1
0
Fork 0
mirror of https://github.com/sourcegraph/jsonrpc2.git synced 2026-06-18 13:10:02 +02:00

Adjust Handler interface and support middleware

This commit is contained in:
Ggicci 2022-01-23 16:36:45 +08:00
parent c9c77b6bb9
commit 4188fa4438
8 changed files with 127 additions and 46 deletions

38
handler.go Normal file
View file

@ -0,0 +1,38 @@
package jsonrpc2
// Handler handles JSON-RPC requests and notifications.
type Handler interface {
// Handle is called to handle a request. No other requests are handled
// until it returns. If you do not require strict ordering behavior
// of received RPCs, it is suggested to wrap your handler in
// AsyncHandler.
Handle(*Conn, *Request)
}
type HandlerFunc func(*Conn, *Request)
func (f HandlerFunc) Handle(conn *Conn, req *Request) {
f(conn, req)
}
type Middleware func(Handler) Handler
type chain struct {
ms []Middleware
}
func Chain(middleware ...Middleware) chain {
return chain{ms: append([]Middleware(nil), middleware...)}
}
func (c chain) Then(h Handler) Handler {
if h == nil {
panic("nil handler")
}
for i := range c.ms {
h = c.ms[len(c.ms)-1-i](h)
}
return h
}