douyouyi8878
2012-01-18 22:27
浏览 114

如何在Go中正确调用JSON-RPC?

I've been trying various configurations in order to call a simple JSON-RPC server for Bitcoin in Go, but didn't manage to get anywhere.

In Python, the entire code looks like:

from jsonrpc import ServiceProxy
access = ServiceProxy("http://user:pass@127.0.0.1:8332")
print access.getinfo()

But in Go, I seem to be bumping into erros like "too many colons in address", or "no such host". I've tried using both of the packages rpc and rpc/jsonrpc, using methods Dial and DialHTTP, using various network parameters and still can't get anywhere.

So, how do I properly call a JSON-RPC server in Go?

图片转代码服务由CSDN问答提供 功能建议

我一直在尝试各种配置,以便调用在Go语言中用于比特币的简单JSON-RPC服务器,但没有成功。 < p>在Python中,整个代码如下:

 从jsonrpc import ServiceProxy 
access = ServiceProxy(“ http:// user:pass@127.0.0.1:8332”)  
print access.getinfo()
   
 
 

但是在Go语言中,我似乎遇到了“地址中的冒号太多” ,或“没有这样的主机”。 我尝试使用rpc和rpc / jsonrpc软件包,使用Dial和DialHTTP方法,使用各种网络参数,但仍然无法到达任何地方。

所以,我如何正确 在Go中调用JSON-RPC服务器?

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

1条回答 默认 最新

  • dtyqflrr775518 2012-01-19 10:18
    已采纳

    The jsonrpc package doesn't support json-rpc over HTTP at the moment. So, you can't use that, sorry.

    But the jsonrpc specification is quite simple and it's probably quite easy to write your own jsonrpchttp (oh, I hope you know a better name) package.

    I was able to call "getinfo" succesfully using the following (horrible) code:

    package main
    
    import (
        "encoding/json"
        "io/ioutil"
        "log"
        "net/http"
        "strings"
    )
    
    func main() {
        data, err := json.Marshal(map[string]interface{}{
            "method": "getinfo",
            "id":     1,
            "params": []interface{}{},
        })
        if err != nil {
            log.Fatalf("Marshal: %v", err)
        }
        resp, err := http.Post("http://bob:secret@127.0.0.1:8332",
            "application/json", strings.NewReader(string(data)))
        if err != nil {
            log.Fatalf("Post: %v", err)
        }
        defer resp.Body.Close()
        body, err := ioutil.ReadAll(resp.Body)
        if err != nil {
            log.Fatalf("ReadAll: %v", err)
        }
        result := make(map[string]interface{})
        err = json.Unmarshal(body, &result)
        if err != nil {
            log.Fatalf("Unmarshal: %v", err)
        }
        log.Println(result)
    }
    

    Maybe you can clean it up a bit by implementing the rpc.ClientCodec interface (see jsonrpc/client.go for an example). Then you can take advantage of Go's rpc package.

    打赏 评论

相关推荐 更多相似问题