2022-05-21 20:38:21 +03:00
2022-01-31 02:31:43 +03:00
# JSON-RPC 2.0
Golang implementation of JSON-RPC 2.0 server with generics.
Go 1.18+ required
## Features:
2022-05-21 20:38:21 +03:00
- [x] HTTP/HTTPS transport
- [x] TCP transport
2022-01-31 20:17:31 +03:00
- [ ] WebSocket transport
2022-01-31 02:31:43 +03:00
2022-01-31 20:17:31 +03:00
## Usage (http transport)
2022-01-31 02:31:43 +03:00
2022-05-21 20:38:21 +03:00
1. Create JSON-RPC server:
```go
import "go.neonxp.dev/jsonrpc2/rpc"
...
s := rpc.New()
```
2. Add required transport(s):
```go
import "go.neonxp.dev/jsonrpc2/transport"
2022-01-31 20:17:31 +03:00
...
2022-05-21 20:38:21 +03:00
s.AddTransport(& transport.HTTP{Bind: ":8000"})
s.AddTransport(& transport.TCP{Bind: ":3000"})
```
3. Write handler:
```go
2022-01-31 02:31:43 +03:00
func Multiply(ctx context.Context, args *Args) (int, error) {
return args.A * args.B, nil
}
2022-05-21 20:38:21 +03:00
```
2022-01-31 02:31:43 +03:00
Handler must have exact two arguments (context and input of any json serializable type) and exact two return values (output of any json serializable type and error)
2022-05-21 20:39:31 +03:00
4. Wrap handler with `rpc.H` method and register it in server:
2022-05-21 20:38:21 +03:00
```go
s.Register("multiply", rpc.H(Multiply))
```
2022-05-21 20:39:31 +03:00
5. Run RPC server:
2022-05-21 20:38:21 +03:00
```go
s.Run(ctx)
```
2022-01-31 02:31:43 +03:00
2022-01-31 20:17:31 +03:00
## Custom transport
2022-05-21 20:38:21 +03:00
Any transport must implement simple interface `transport.Transport` :
```go
type Transport interface {
Run(ctx context.Context, resolver Resolver) error
}
```
2022-01-31 20:17:31 +03:00
2022-01-31 02:31:43 +03:00
## Complete example
2022-05-21 20:38:21 +03:00
[Full code ](/example )
2022-01-31 02:31:43 +03:00
```go
package main
import (
2022-01-31 20:17:31 +03:00
"context"
2022-01-31 02:31:43 +03:00
2022-03-24 18:37:38 +03:00
"go.neonxp.dev/jsonrpc2/rpc"
2022-05-21 20:38:21 +03:00
"go.neonxp.dev/jsonrpc2/transport"
2022-01-31 02:31:43 +03:00
)
func main() {
2022-05-21 20:38:21 +03:00
s := rpc.New()
s.AddTransport(& transport.HTTP{Bind: ":8000"}) // HTTP transport
s.AddTransport(& transport.TCP{Bind: ":3000"}) // TCP transport
2022-01-31 02:31:43 +03:00
2022-05-21 20:38:21 +03:00
s.Register("multiply", rpc.H(Multiply))
s.Register("divide", rpc.H(Divide))
s.Run(context.Background())
2022-01-31 02:31:43 +03:00
}
func Multiply(ctx context.Context, args *Args) (int, error) {
//...
}
func Divide(ctx context.Context, args *Args) (*Quotient, error) {
//...
}
type Args struct {
A int `json:"a"`
B int `json:"b"`
}
type Quotient struct {
Quo int `json:"quo"`
Rem int `json:"rem"`
}
2022-01-31 20:55:38 +03:00
```
## Author
Alexander Kiryukhin < i @ neonxp . dev >
## License
2022-03-24 18:37:38 +03:00
![GPL v3 ](https://www.gnu.org/graphics/gplv3-with-text-136x68.png )
2022-05-21 20:38:21 +03:00