Skip to content

Repository files navigation

github.com/AdamSLevy/jsonrpc2/v14

GoDocGo Report CardCoverage StatusBuild Status

Package jsonrpc2 is a complete and strictly conforming implementation of the JSON-RPC 2.0 protocol for both clients and servers.

The full specification can be found at https://www.jsonrpc.org.

Clients

The simplest way to make a JSON-RPC 2.0 request is to use the provided Client.Request.

varc jsonrpc2.Clientparams:= []float64{1, 2, 3}
varresultinterr:=c.Request(nil, "http://localhost:8080", "sum", params, &result)
if_, ok:=err.(jsonrpc2.Error); ok {
// received Error Request
}
iferr!=nil {
// some JSON marshaling or network error
}
fmt.Printf("The sum of %v is %v.\n", params, result)

For clients that do not wish to use the provided Client, the Request and Response types can be used directly.

req, _:=json.Marshal(jsonrpc2.Request{Method: "subtract",
Params: []int{5, 1},
ID: 0,
})
httpRes, _:=http.Post("www.example.com", "application/json",
bytes.NewReader(req))
resBytes, _:=ioutil.ReadAll(httpRes.Body)
res:= jsonrpc2.Response{Result: &MyCustomResultType{}, ID: new(int)}
json.Unmarshal(respBytes, &res)

Servers

Servers define their own MethodFuncs and associate them with a name in a MethodMap that is passed to HTTPRequestHandler() to return a corresponding http.HandlerFunc. See HTTPRequestHandler for more details.

funcgetUser(ctx context.Context, params json.RawMessage) interface{} {
varuUseriferr:=json.Unmarshal(params, &u); err!=nil {
returnjsonrpc2.InvalidParams(err)
}
conn, err:=mydbpkg.GetDBConn()
iferr!=nil {
// The handler will recover, print debug info if enabled, and// return an Internal Error to the client.panic(err)
}
iferr:=u.Select(conn); err!=nil {
returnjsonrpc2.NewError(-30000, "user not found", u.ID)
}
returnu
}
funcStartServer() {
methods:= jsonrpc2.MethodMap{"version": versionMethod}
http.ListenAndServe(":8080", jsonrpc2.HTTPRequestHandler(methods))
}

About

Golang package for implementing a JSON RPC 2.0 server or client.

Resources

Stars

12 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages