[Ethereum] How to communicate with the JSON RPC server programmatically using Go

go-ethereumgolangjson-rpc

Is there a way to interact with the JSON RPC server directly in Go?

I tried the following:

  1. Starting the RPC Server with "geth –rpc"

  2. Running the following code:

    package main
    
    import (
        "fmt"
    
        "github.com/ethereum/go-ethereum/rpc"
        "github.com/ethereum/go-ethereum/rpc/comms"
    )
    
    func main() {
    
        client, err := comms.ClientFromEndpoint("rpc:127.0.0.1", 0)
        if err != nil {
            panic(err)
        }
    
        xeth := rpc.NewXeth(client)
    
        type p interface {
        }
    
        response := make(map[string]interface{}, 0)
        var params []interface{}
        response, err = xeth.Call("eth_gasPrice", params)
    
        if err != nil {
            panic(err)
        }
    
        fmt.Println(response)
    }
    

The connection seems to work, but I get the following error:

panic: interface conversion: interface {} is string, not map[string]interface {}

goroutine 1 [running]:
panic(0x48c3d00, 0xc820098380)
    /usr/local/go/src/runtime/panic.go:481 +0x3e6
github.com/ethereum/go-ethereum/rpc.(*Xeth).Call(0xc8201bdc80, 0x49ee5f0, 0xc, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0)
    /Users/tim/Documents/go_workspace/src/github.com/ethereum/go-ethereum/rpc/xeth.go:72 +0x4dc
main.main()
    /Users/tim/Documents/go_workspace/src/eth_test/main.go:23 +0x12e
exit status 2

If I change the "Call" method here: https://github.com/ethereum/go-ethereum/blob/master/rpc/xeth.go, I can change the type assertion to the right type and I get the correct result back.

Apart from that, the comments in the linked file (xeth.go) tell that it is an interface to a remote node, I however want an interface to a local node.

I figured that it must be possible to first start the RPC server (that is otherwise started with "geth –rpc" on the console) purely programmatically since the console command will call Go methods after all and second it should be possible to send RPC requests using GO.

What am I doing wrong here?

Best Answer

You might take a look at a simplistic approach we took for etherapis: https://github.com/etherapis/etherapis/blob/master/etherapis/geth/api.go

However there's an RPC client in the works that should already support subscriptions too. Not sure when Felix will open his PR with it though.

Related Topic