lotus/lib/jsonrpc/server.go

88 lines
1.6 KiB
Go
Raw Normal View History

2019-07-12 17:12:38 +00:00
package jsonrpc
import (
"encoding/json"
"io"
"net/http"
"github.com/gorilla/websocket"
)
const (
rpcParseError = -32700
rpcMethodNotFound = -32601
rpcInvalidParams = -32602
)
// RPCServer provides a jsonrpc 2.0 http server handler
type RPCServer struct {
methods handlers
}
// NewServer creates new RPCServer instance
func NewServer() *RPCServer {
return &RPCServer{
methods: map[string]rpcHandler{},
}
}
var upgrader = websocket.Upgrader{}
func (s *RPCServer) handleWS(w http.ResponseWriter, r *http.Request) {
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Error(err)
w.WriteHeader(500)
return
}
handleWsConn(r.Context(), c, s.methods, nil, nil)
2019-07-15 16:32:43 +00:00
if err := c.Close(); err != nil {
log.Error(err)
return
}
2019-07-12 17:12:38 +00:00
}
// TODO: return errors to clients per spec
func (s *RPCServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Connection") == "Upgrade" {
s.handleWS(w, r)
return
}
2019-07-15 16:21:48 +00:00
s.methods.handleReader(r.Context(), r.Body, w, rpcError)
2019-07-12 17:12:38 +00:00
}
2019-07-15 16:21:48 +00:00
func rpcError(wf func(func(io.Writer)), req *request, code int, err error) {
wf(func(w io.Writer) {
if hw, ok := w.(http.ResponseWriter); ok {
hw.WriteHeader(500)
}
2019-07-12 17:12:38 +00:00
2019-07-15 16:21:48 +00:00
if req.ID == nil { // notification
return
}
resp := response{
Jsonrpc: "2.0",
ID: *req.ID,
Error: &respError{
Code: code,
Message: err.Error(),
},
}
2019-07-12 17:12:38 +00:00
2019-07-15 16:21:48 +00:00
_ = json.NewEncoder(w).Encode(resp)
})
2019-07-12 17:12:38 +00:00
}
// Register registers new RPC handler
//
// Handler is any value with methods defined
func (s *RPCServer) Register(namespace string, handler interface{}) {
s.methods.register(namespace, handler)
}
var _ error = &respError{}