description: Tutorial on how to set up a client to connect to Ethereum with Go.

Setting up the Client

Setting up the Ethereum client in Go is a fundamental step required for interacting with the blockchain. First import the ethclient go-ethereum package and initialize it by calling Dial which accepts a provider URL.

You can connect to the infura gateway if you don’t have an existing client. Infura manages a bunch of Ethereum [geth and parity] nodes that are secure, reliable, scalable and lowers the barrier to entry for newcomers when it comes to plugging into the Ethereum network.

  1. client, err := ethclient.Dial("https://mainnet.infura.io")

You may also pass the path to the IPC endpoint file if you have a local instance of geth running.

  1. client, err := ethclient.Dial("/home/user/.ethereum/geth.ipc")

Using the ethclient is a necessary thing you’ll need to start with for every Go Ethereum project and you’ll be seeing this step a lot throughout this book.

Using Ganache

Ganache (formally known as testrpc) is an Ethereum implementation written in Node.js meant for testing purposes while developing dapps locally. Here we’ll walk you through how to install it and connect to it.

First install ganache via NPM.

  1. npm install -g ganache-cli

Then run the ganache CLI client.

  1. ganache-cli

Now connect to the ganache RPC host on http://localhost:8545.

  1. client, err := ethclient.Dial("http://localhost:8545")
  2. if err != nil {
  3. log.Fatal(err)
  4. }

You may also use the same mnemonic when starting ganache to generate the same sequence of public addresses.

  1. ganache-cli -m "much repair shock carbon improve miss forget sock include bullet interest solution"

I highly recommend getting familiar with ganache by reading their documentation.

Full code

client.go

  1. package main
  2. import (
  3. "fmt"
  4. "log"
  5. "github.com/ethereum/go-ethereum/ethclient"
  6. )
  7. func main() {
  8. client, err := ethclient.Dial("https://mainnet.infura.io")
  9. if err != nil {
  10. log.Fatal(err)
  11. }
  12. fmt.Println("we have a connection")
  13. _ = client // we'll use this in the upcoming sections
  14. }