Parse and Serialize JSON-RPC2 messages in golang
https://www.jsonrpc.org/specification
Interface Inspired by https://github.com/teambition/jsonrpc-lite
ID Fork from golang.org/x/tools/internal/jsonrpc2@feee8acb394c170fe9eb4eb9f538b8877d9a3cd4
- No depend
- Only Parse and Serialize JSON-RPC2 messages
- No
net.Conn
,http
,websocket
control, You can use any protocol - Support batch
package main
import (
"fmt"
"github.com/sb-im/jsonrpc-lite"
)
func main() {
recv := []byte(`
{"jsonrpc": "2.0", "method": "subtract", "params": [42, 23], "id": 1}
`)
fmt.Printf("Server RECV: %s\n", recv)
rpc := jsonrpc.ParseObject(recv)
if rpc.Type != jsonrpc.TypeRequest {
panic("Not jsonrpc.TypeRequest")
}
send, err := jsonrpc.NewSuccess(rpc.ID, rpc).ToJSON()
if err != nil {
panic(err)
}
fmt.Printf("Server SEND: %s\n", send)
}
// alone
rpc := jsonrpc.ParseObject([]byte(`
{"jsonrpc": "2.0", "method": "subtract", "params": {"subtrahend": 23, "minuend": 42}, "id": 3}`
))
if rpc.Type != jsonrpc.TypeRequest {
fmt.Println(rpc)
}
// Batch
rpcs := jsonrpc.Batch([]byte(`
[
{"jsonrpc": "2.0", "method": "sum", "params": [1,2,4], "id": "1"},
{"jsonrpc": "2.0", "method": "notify_hello", "params": [7]},
{"jsonrpc": "2.0", "method": "subtract", "params": [42,23], "id": "2"},
{"foo": "boo"},
{"jsonrpc": "2.0", "method": "foo.get", "params": {"name": "myself"}, "id": "5"},
{"jsonrpc": "2.0", "method": "get_data", "id": "9"}
]
`))
for i, rpc := range rpcs {
fmt.Println(i, rpc)
}
data, err := jsonrpc.NewRequest("123", "test", []string{"sss", "zzz"}).ToJSON()
if err != nil {
panic(err)
}
fmt.Printf("%s\n", data)
data, err := jsonrpc.NewNotify("test", []string{"sss", "zzz"}).ToJSON()
if err != nil {
panic(err)
}
fmt.Printf("%s\n", data)
data, err := jsonrpc.NewSuccess(1234, []string{"sss", "zzz"}).ToJSON()
if err != nil {
panic(err)
}
fmt.Printf("%s\n", data)
Custom error
// NewError
data, err := jsonrpc.NewError(233, 1, "This is Error", []string{"sss", "zzz"}).ToJSON()
if err != nil {
panic(err)
}
fmt.Printf("%s\n", data)
The error codes from and including -32768 to -32000 are reserved for pre-defined error
// NewErrors
res := jsonrpc.NewErrors(1234)
res.Errors.ParseError([]string{"data", "data2"})
data, err := res.ToJSON()
if err != nil {
panic(err)
}
fmt.Printf("%s\n", data)
- Automatic verification
ToJSON()
is JSON-RPC 2.0 Specification