-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathrpcMux.go
45 lines (34 loc) · 862 Bytes
/
rpcMux.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
package DaedalusLanguageServer
import (
"context"
"fmt"
"github.com/goccy/go-json"
"go.lsp.dev/jsonrpc2"
)
type Handler func(RpcContext) error
func NewMux() *RpcMux {
return &RpcMux{
pathToType: map[string]Handler{},
}
}
type RpcMux struct {
pathToType map[string]Handler
}
func (d *RpcMux) Handle(ctx context.Context, reply jsonrpc2.Replier, req jsonrpc2.Request) (bool, error) {
if handler, ok := d.pathToType[req.Method()]; ok {
return true, handler(rpcContext{ctx, reply, req})
}
return false, fmt.Errorf("no handler")
}
func (d *RpcMux) Register(p string, fn Handler) {
d.pathToType[p] = fn
}
func MakeHandler[T any](fn func(req RpcContext, data T) error) Handler {
return func(req RpcContext) error {
var val T
if err := json.Unmarshal(req.Request().Params(), &val); err != nil {
return err
}
return fn(req, val)
}
}