Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

In Python, the entire code looks like:

from jsonrpc import ServiceProxy
access = ServiceProxy("http://user:[email protected]: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?

like image 588
ThePiachu Avatar asked Jan 18 '12 22:01

ThePiachu


1 Answers

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:[email protected]: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.

like image 75
tux21b Avatar answered Sep 28 '22 06:09

tux21b