/
rpc.go
85 lines (67 loc) · 2.22 KB
/
rpc.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// Copyright 2018 The QOS Authors
package types
import (
"encoding/json"
"net/http"
"github.com/pkg/errors"
amino "github.com/tendermint/go-amino"
)
const (
UrlPrefixNodes = "/nodes"
UrlNodeProxy = UrlPrefixNodes + "/:nodeName"
UrlPrefixPlugins = "/plugins"
)
type RPCResponse struct {
JSONRPC string `json:"jsonrpc"`
ID string `json:"id"`
Result interface{} `json:"result,omitempty"`
Error *RPCError `json:"error,omitempty"`
}
type RPCError struct {
Code int `json:"code"`
Message string `json:"message"`
Data string `json:"data,omitempty"`
}
func NewRPCErrorResponse(id string, code int, msg string, data string) RPCResponse {
return RPCResponse{
JSONRPC: "2.0",
ID: id,
Error: &RPCError{Code: code, Message: msg, Data: data},
}
}
func NewRPCSuccessResponse(cdc *amino.Codec, id string, res interface{}) RPCResponse {
var rawMsg json.RawMessage
if res != nil {
var js []byte
js, err := cdc.MarshalJSON(res)
if err != nil {
return RPCInternalError(id, errors.Wrap(err, "Error marshalling response"))
}
rawMsg = json.RawMessage(js)
}
return RPCResponse{JSONRPC: "2.0", ID: id, Result: rawMsg}
}
func RPCParseError(id string, err error) RPCResponse {
return NewRPCErrorResponse(id, -32700, "Parse error. Invalid JSON", err.Error())
}
func RPCInvalidRequestError(id string, err error) RPCResponse {
return NewRPCErrorResponse(id, -32600, "Invalid Request", err.Error())
}
func RPCMethodNotFoundError(id string) RPCResponse {
return NewRPCErrorResponse(id, -32601, "Method not found", "")
}
func RPCInvalidParamsError(id string, err error) RPCResponse {
return NewRPCErrorResponse(id, -32602, "Invalid params", err.Error())
}
func RPCUnauthorizedError(id string, err error) RPCResponse {
return NewRPCErrorResponse(id, http.StatusUnauthorized, "Unauthorized", err.Error())
}
func RPCForbiddenError(id string, err error) RPCResponse {
return NewRPCErrorResponse(id, http.StatusForbidden, "Forbidden", err.Error())
}
func RPCInternalError(id string, err error) RPCResponse {
return NewRPCErrorResponse(id, -32603, err.Error(), "Internal error")
}
func RPCServerError(id string, err error) RPCResponse {
return NewRPCErrorResponse(id, -32000, "Server error", err.Error())
}