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:
- [x] Batch request and responses
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-01-31 20:17:31 +03:00
1. Create JSON-RPC/HTTP server:
2022-01-31 02:31:43 +03:00
```go
2022-01-31 20:17:31 +03:00
import "github.com/neonxp/jsonrpc2/http"
...
s := http.New()
2022-01-31 02:31:43 +03:00
```
2. Write handler:
```go
func Multiply(ctx context.Context, args *Args) (int, error) {
return args.A * args.B, nil
}
```
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-01-31 20:17:31 +03:00
3. Wrap handler with `rpc.Wrap` method and register it in server:
2022-01-31 02:31:43 +03:00
```go
2022-01-31 20:17:31 +03:00
s.Register("multiply", rpc.Wrap(Multiply))
2022-01-31 02:31:43 +03:00
```
4. Use server as common http handler:
```go
http.ListenAndServe(":8000", s)
```
2022-01-31 20:17:31 +03:00
## Custom transport
See [http/server.go ](/http/server.go ) for example of transport implementation.
2022-01-31 02:31:43 +03:00
## Complete example
[Full code ](/examples/http )
```go
package main
import (
2022-01-31 20:17:31 +03:00
"context"
"net/http"
2022-01-31 02:31:43 +03:00
2022-01-31 20:17:31 +03:00
httpRPC "github.com/neonxp/jsonrpc2/http"
"github.com/neonxp/jsonrpc2/rpc"
2022-01-31 02:31:43 +03:00
)
func main() {
2022-01-31 20:17:31 +03:00
s := httpRPC.New()
s.Register("multiply", rpc.Wrap(Multiply))
s.Register("divide", rpc.Wrap(Divide))
2022-01-31 02:31:43 +03:00
2022-01-31 20:17:31 +03:00
http.ListenAndServe(":8000", s)
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
![GPL v3 ](https://www.gnu.org/graphics/gplv3-with-text-136x68.png )