[Ethereum] How to get the current block number using Golang

go-ethereum

It's a seemingly simple operation but I can't find an obvious way to do this using the go-ethereum library.

Given a blockchain client like so:

client, err := ethclient.Dial("http://localhost:8545")

The only available methods are:

BalanceAt
BlockByHash
BlockByNumber
CallContract
Close
CodeAt
EstimateGas
FilterLogs
HeaderByHash
HeaderByNumber
NetworkID
NonceAt
PendingBalanceAt
PendingCallContract
PendingCodeAt
PendingNonceAt
PendingStorageAt
PendingTransactionCount
SendTransaction
StorageAt
SubscribeFilterLogs
SubscribeNewHead
SuggestGasPrice
SyncProgress
TransactionByHash
TransactionCount
TransactionInBlock
TransactionReceipt
TransactionSender

Which does not include GetBlockNumber like it does in web3.js for example.

Best Answer

Here's a full example of how to get the current (highest) block number using Go (from the Ethereum Development with Go book):

package main

import (
    "context"
    "fmt"
    "log"
    "math/big"

    "github.com/ethereum/go-ethereum/ethclient"
)

func main() {
    client, err := ethclient.Dial("https://mainnet.infura.io")
    if err != nil {
        log.Fatal(err)
    }

    header, err := client.HeaderByNumber(context.Background(), nil)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(header.Number.String()) // 5671744
}