user9946708
user9946708

Reputation:

How to pass multiple arguments to golang net rpc call

I am using net library in go and I want to make RPC call:

Client.Call("action", []string{"arg1", "arg2"}, &response)

But in JSON I see:

{"method":"action","params":[["arg1","arg2"]],"id":0}

Notice that arguments are enclosed with double square brackets.

In my case I need params to be a simple list:

{"method":"action","params":["arg1","arg2"],"id":0}

Any ideas how to accomplish this?

Upvotes: 4

Views: 2010

Answers (1)

eugenioy
eugenioy

Reputation: 12393

The codec that Go's JSON RPC uses on top of the rpc.Client will take whatever param you send and encode that as the first element of the array it uses for the params.

So the encoded request will always have a top level array with just one element, which will contain the params you sent, as you already noted.

See the WriteRequest function here:

https://golang.org/src/net/rpc/jsonrpc/client.go#L57

To achieve what you want, you can implement a custom rpc.ClientCodec.

The interface is documented here:

https://golang.org/pkg/net/rpc/#ClientCodec

You can borrow almost all of the implementation for the default JSON codec here:

https://golang.org/src/net/rpc/jsonrpc/client.go

And modify the params attribute of the request to read:

Params interface{} `json:"params"`

Then when writing your WriteRequest based on the standard one, you can just assign your params to the request params:

c.req.Params[0] = param

You can then use the rpc.NewClientWithCodec to create a client using your custom codec:

https://golang.org/pkg/net/rpc/#NewClientWithCodec

Upvotes: 2

Related Questions