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

如何将多个参数传递给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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch