Newer
Older
// A value of this type can a JSON-RPC request, notification, successful response or
// error response. Which one it is depends on the fields.
Method string `json:"method,omitempty"`
Params json.RawMessage `json:"params,omitempty"`
Result json.RawMessage `json:"result,omitempty"`
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
func (m *Message) MarshalJSON() ([]byte, error) {
var enc jx.Encoder
// use encoder
enc.Obj(func(e *jx.Encoder) {
e.Field("jsonrpc", func(e *jx.Encoder) {
e.Str("2.0")
})
if m.ID != nil {
e.Field("id", func(e *jx.Encoder) {
e.Raw(m.ID.RawMessage())
})
}
e.Field("method", func(e *jx.Encoder) {
e.Str(m.Method)
})
if m.Error == nil {
e.Field("error", func(e *jx.Encoder) {
xs, _ := json.Marshal(m.Error)
e.Raw(xs)
})
}
if len(m.Params) != 0 {
e.Field("params", func(e *jx.Encoder) {
e.Raw(m.Params)
})
}
if len(m.Result) != 0 {
e.Field("result", func(e *jx.Encoder) {
e.Raw(m.Result)
})
}
})
// output
return enc.Bytes(), nil
}
func MakeCall(id int, method string, params []any) *Message {
return &Message{
return msg.hasValidID() && len(msg.Method) == 0 && msg.Params == nil && (msg.Result != nil || msg.Error != nil)
b, _ := json.Marshal(msg)
func (msg *Message) ErrorResponse(err error) *Message {
resp := ErrorMessage(err)
enc, err := jzon.Marshal(result)
Code int `json:"code"`
Message string `json:"message"`
Data any `json:"data,omitempty"`
}
// error message produces json rpc message with error message
Message: err.Error(),
}}
ec, ok := err.(Error)
if ok {
msg.Error.Code = ec.ErrorCode()
}
de, ok := err.(DataError)
if ok {
msg.Error.Data = de.ErrorData()
}
return msg
}
// isBatch returns true when the first non-whitespace characters is '['
for _, c := range raw {
// skip insignificant whitespace (http://www.ietf.org/rfc/rfc4627.txt)
switch c {
case 0x20, 0x09, 0x0a, 0x0d:
continue
}
// parseMessage parses raw bytes as a (batch of) JSON-RPC message(s). There are no error
// checks in this function because the raw message has already been syntax-checked when it
// is called. Any non-JSON-RPC messages in the input return the zero value of
// Message.
func ParseMessage(raw json.RawMessage) ([]*Message, bool) {
if !IsBatchMessage(raw) {
msgs := []*Message{{}}
jzon.Unmarshal(raw, &msgs[0])
// TODO:
// for some reason other json decoders are incompatible with our test suite
dec.Arr(func(d *jx.Decoder) error {
msg := new(Message)
raw, err := d.Raw()
if err != nil {
return nil
}
err = json.Unmarshal(raw, msg)
if err != nil {
msg = nil
}
msgs = append(msgs, msg)
return nil
})