Golang implementation of JSON-RPC 2.0 server with generics
Go to file
Alexander Kiryukhin d4708a3665
Changed package name to `go.neonxp.dev/jsonrpc2`
2022-03-24 18:37:38 +03:00
examples/http Changed package name to `go.neonxp.dev/jsonrpc2` 2022-03-24 18:37:38 +03:00
http Changed package name to `go.neonxp.dev/jsonrpc2` 2022-03-24 18:37:38 +03:00
rpc Changed package name to `go.neonxp.dev/jsonrpc2` 2022-03-24 18:37:38 +03:00
LICENSE.md Added license 2022-01-31 20:55:38 +03:00
README.md Changed package name to `go.neonxp.dev/jsonrpc2` 2022-03-24 18:37:38 +03:00
go.mod Changed package name to `go.neonxp.dev/jsonrpc2` 2022-03-24 18:37:38 +03:00

README.md

JSON-RPC 2.0

Golang implementation of JSON-RPC 2.0 server with generics.

Go 1.18+ required

Features:

  • Batch request and responses
  • WebSocket transport

Usage (http transport)

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

Custom transport

See http/server.go for example of transport implementation.

Complete example

Full code

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