简体   繁体   English

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

[英]How to properly call JSON-RPC in Go?

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. 我一直在尝试各种配置,以便在Go中为Bitcoin调用一个简单的JSON-RPC服务器 ,但是没有设法获得任何地方。

In Python, the entire code looks like: 在Python中,整个代码如下所示:

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". 但是在Go中,我似乎碰到了像“地址中的冒号太多”或“没有这样的主人”这样的错误。 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. 我尝试过使用rpc和rpc / jsonrpc这两个软件包,使用Dial和DialHTTP方法,使用各种网络参数,仍然无法到达任何地方。

So, how do I properly call a JSON-RPC server in Go? 那么,如何在Go中正确调用JSON-RPC服务器?

The jsonrpc package doesn't support json-rpc over HTTP at the moment. jsonrpc包目前不支持HTTP上的json-rpc。 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. jsonrpc规范非常简单,你可能很容易编写自己的jsonrpchttp (哦,我希望你知道一个更好的名字)包。

I was able to call "getinfo" succesfully using the following (horrible) code: 我能够使用以下(可怕的)代码成功调用“getinfo”:

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). 也许你可以通过实现rpc.ClientCodec接口来清理它(例如,参见jsonrpc / client.go )。 Then you can take advantage of Go's rpc package. 然后你可以利用Go的rpc包。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM