morffix/rpc/server.go
2024-04-28 01:58:45 +02:00

42 lines
1,012 B
Go

package rpc
import (
"context"
"encoding/json"
"fmt"
"nhooyr.io/websocket"
)
const ERROR_JRPC2_PARSE_ERROR = -32700
const ERROR_JRPC2_METHOD_NOT_FOUND = -32601
const ERROR_JRPC2_INTERNAL = -32603
func NewServer() *server {
return &server{
methods: make(map[string]func(context.Context, Request) (any, error)),
requests: make(map[string]chan *Response, 1),
}
}
func (s *server) RegisterMethod(name string, method func(context.Context, Request) (any, error)) {
s.methods[name] = method
}
// TODO Method With Multiple Responses
func (s *server) HandleMessage(ctx context.Context, c *websocket.Conn, data []byte) {
var message Message
err := json.Unmarshal(data, &message)
if err != nil {
respondError(ctx, c, "", ERROR_JRPC2_PARSE_ERROR, fmt.Errorf("Error Parsing Message: %w", err), nil)
return
}
// Check if this is a Request or a Response with the Existance of the Method field
if message.Method != nil {
s.handleRequest(ctx, c, data)
} else {
s.handleResponse(ctx, data)
}
}