78 lines
1.3 KiB
Go
78 lines
1.3 KiB
Go
package jsonrpc
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
|
|
"go.uber.org/zap"
|
|
|
|
"git.loafle.net/commons_go/logging"
|
|
ogw "git.loafle.net/overflow/overflow_gateway_websocket"
|
|
)
|
|
|
|
type JSONRpc interface {
|
|
ogw.ProtocolHandler
|
|
}
|
|
|
|
type jsonRpc struct {
|
|
ctx context.Context
|
|
logger *zap.Logger
|
|
jh JSONRpcHandler
|
|
}
|
|
|
|
func New(ctx context.Context, jh JSONRpcHandler) JSONRpc {
|
|
jr := &jsonRpc{
|
|
ctx: ctx,
|
|
logger: logging.WithContext(ctx),
|
|
jh: jh,
|
|
}
|
|
|
|
return jr
|
|
}
|
|
|
|
func (jr *jsonRpc) OnMessage(soc ogw.Socket, messageType int, r io.Reader) []byte {
|
|
var err error
|
|
req := &ServerRequest{}
|
|
err = json.NewDecoder(r).Decode(req)
|
|
if err != nil {
|
|
}
|
|
|
|
var result []byte
|
|
|
|
if nil != req.Id {
|
|
result = jr.onRequest(soc, req)
|
|
} else {
|
|
jr.onNotify(soc, req)
|
|
}
|
|
|
|
return result
|
|
}
|
|
|
|
func (jr *jsonRpc) onRequest(soc ogw.Socket, req *ServerRequest) []byte {
|
|
var err error
|
|
result, err := jr.jh.OnRequest(soc, req.Method, req.Params)
|
|
|
|
res := &ServerResponse{
|
|
Protocol: req.Protocol,
|
|
Result: result,
|
|
Error: err,
|
|
Id: req.Id,
|
|
}
|
|
|
|
j, err := json.Marshal(res)
|
|
if nil != err {
|
|
jr.logger.Error(fmt.Sprintf("JSON RPC error: %v", err))
|
|
}
|
|
|
|
return j
|
|
}
|
|
|
|
func (jr *jsonRpc) onNotify(soc ogw.Socket, req *ServerRequest) {
|
|
err := jr.jh.OnNotify(soc, req.Method, req.Params)
|
|
if nil != err {
|
|
jr.logger.Error(fmt.Sprintf("JSON RPC error: %v", err))
|
|
}
|
|
}
|