JSON RPC Client Go

南楼画角 提交于 2019-12-12 01:49:43

问题


I have a python server serving response through JSON-RPC. Here is a sample response from the server.

'{"jsonrpc": "2.0", "result": "Peer 1: local 10.10.0.2  remote 10.10.0.1  state CONNECT\\nPeer 2: local 10.10.0.18  remote 10.10.0.17  state ESTABLISHED\\nPeer 3: local 10.10.0.10  remote 10.10.0.9  state ESTABLISHED", "id": "839732f9-cf36-46ff-8b9b-6120250d9ce5"}'

Here is the request I need to send to the server:

'{"method":"echo","jsonrpc":"2.0","params":["test_params"],"id":"839732f9-cf36-46ff-8b9b-6120250d9ce5"}'

Here is my client with go language:

package main

import (
    "fmt"
    "log"
    "net"
    "net/rpc/jsonrpc"
)
type Args struct {
    jsonrpc, id string
}

func main() {
    conn, err := net.Dial("tcp", "11.21.22.221:8080")
    if err != nil {
        panic(err)
    }
    defer conn.Close()

    args := Args{"2.0", "d87198f0-af92-49f8-9a7d-ab8bed5c4d17"}
    var reply string

    c := jsonrpc.NewClient(conn)

    err = c.Call("echo", args, &reply)
    if err != nil {
        log.Fatal("error:", err)
    }
    fmt.Printf("Response: %d", reply)
}

But, when I run this client, it is not sending anything in the params. Instead it is sending empty params like this:

'{"method":"echo","params":[{}],"id":0}\n

Can somebody help me telling what mistake I am making? I am a newbie to go language.

Thanks.


回答1:


I don't think what you are doing is possible using the client as provided by go because the private clientRequest struct is currently defined as:

    type clientRequest struct {
        Method string         `json:"method"`
        Params [1]interface{} `json:"params"`
        Id     uint64         `json:"id"`
    }

What you pass into Call as args is stuck into Params and note how there is no "Version `json:"jsonrpc"`" inside of that struct.

AFAICT (which may be wrong, this is my first time reading through this code) you would need to implement your own ClientCodec. You could probably get away with copying most (all) of the parts out of the stdlib and add the field to the clientRequest above. ;-)



来源:https://stackoverflow.com/questions/29479360/json-rpc-client-go

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!