drl9940
2018-07-04 21:25
浏览 193
已采纳

如何将多个参数传递给golang net rpc调用

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?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dsrruefh12970 2018-07-04 22:19
    已采纳

    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

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题