aboutsummaryrefslogtreecommitdiff
path: root/README.md
blob: 5938fdf98aad0d8324c826fe5d4845dc5d448a4a (plain) (blame)
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
86
87
88
89
# JSON-RPC 2.0

Golang implementation of JSON-RPC 2.0 server with generics.

Go 1.18+ required

## Features:

- [x] Batch request and responses
- [ ] WebSocket transport

## Usage (http transport)

1. Create JSON-RPC/HTTP server:
    ```go
    import "go.neonxp.dev/jsonrpc2/http"
    ...
    s := http.New()
    ```
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)
3. Wrap handler with `rpc.Wrap` method and register it in server:
    ```go
    s.Register("multiply", rpc.Wrap(Multiply))
    ```
4. Use server as common http handler:
    ```go
    http.ListenAndServe(":8000", s)
    ```

## Custom transport

See [http/server.go](/http/server.go) for example of transport implementation.

## Complete example

[Full code](/examples/http)

```go
package main

import (
   "context"
   "net/http"

   httpRPC "go.neonxp.dev/jsonrpc2/http"
   "go.neonxp.dev/jsonrpc2/rpc"
)

func main() {
   s := httpRPC.New()
   s.Register("multiply", rpc.Wrap(Multiply))
   s.Register("divide", rpc.Wrap(Divide))

   http.ListenAndServe(":8000", s)
}

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"`
}

```

## Author

Alexander Kiryukhin <i@neonxp.dev>

## License

![GPL v3](https://www.gnu.org/graphics/gplv3-with-text-136x68.png)