Anton Kaliaev c08618f7e9 | 7 years ago | |
---|---|---|
.. | ||
client | 7 years ago | |
server | 8 years ago | |
test | 7 years ago | |
types | 7 years ago | |
Dockerfile | 8 years ago | |
Makefile | 8 years ago | |
README.md | 8 years ago | |
circle.yml | 8 years ago | |
rpc_test.go | 7 years ago | |
version.go | 8 years ago |
HTTP RPC server supporting calls via uri params, jsonrpc, and jsonrpc over websockets
Suppose we want to expose the rpc function HelloWorld(name string, num int)
.
As a GET request, it would have URI encoded parameters, and look like:
curl 'http://localhost:8008/hello_world?name="my_world"&num=5'
Note the '
around the url, which is just so bash doesn't ignore the quotes in "my_world"
.
This should also work:
curl http://localhost:8008/hello_world?name=\"my_world\"&num=5
A GET request to /
returns a list of available endpoints.
For those which take arguments, the arguments will be listed in order, with _
where the actual value should be.
As a POST request, we use JSONRPC. For instance, the same request would have this as the body:
{
"jsonrpc": "2.0",
"id": "anything",
"method": "hello_world",
"params": {
"name": "my_world",
"num": 5
}
}
With the above saved in file data.json
, we can make the request with
curl --data @data.json http://localhost:8008
All requests are exposed over websocket in the same form as the POST JSONRPC.
Websocket connections are available at their own endpoint, typically /websocket
,
though this is configurable when starting the server.
Define some types and routes:
type ResultStatus struct {
Value string
}
// Define some routes
var Routes = map[string]*rpcserver.RPCFunc{
"status": rpcserver.NewRPCFunc(Status, "arg"),
}
// an rpc function
func Status(v string) (*ResultStatus, error) {
return &ResultStatus{v}, nil
}
Now start the server:
mux := http.NewServeMux()
rpcserver.RegisterRPCFuncs(mux, Routes)
wm := rpcserver.NewWebsocketManager(Routes, nil)
mux.HandleFunc("/websocket", wm.WebsocketHandler)
logger := log.NewTMLogger(log.NewSyncWriter(os.Stdout))
go func() {
_, err := rpcserver.StartHTTPServer("0.0.0.0:8008", mux, logger)
if err != nil {
panic(err)
}
}()
Note that unix sockets are supported as well (eg. /path/to/socket
instead of 0.0.0.0:8008
)
Now see all available endpoints by sending a GET request to 0.0.0.0:8008
.
Each route is available as a GET request, as a JSONRPCv2 POST request, and via JSONRPCv2 over websockets.
BREAKING CHANGES:
Client
empty interfaceClientJSONRPC#Call
params
argument became a mapClientURI
-> URIClient
, ClientJSONRPC
-> JSONRPCClient
IMPROVEMENTS:
HTTPClient
interface, which can be used for both ClientURI
and ClientJSONRPC
Call
method to WSClient
(see method's doc for details)