一、使用geth方法
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
}
二、使用rpc方法
func GetBlockNumber(client *rpc.Client) int {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
type Block struct {
Number string
}
var lastBlock Block
err := client.CallContext(ctx, &lastBlock, "eth_getBlockByNumber", "latest", true)
if err != nil {
fmt.Println("can't get latest block:", err)
return 0
}
var blockNumber, err1 = strconv.ParseInt(lastBlock.Number, 0, 64)
//blockNumber, err1 := strconv.Atoi(lastBlock.Number)
if err1 != nil {
fmt.Println("strconv error:", err1)
return 0
}
fmt.Println("number: ", blockNumber)
return int(blockNumber)
}
网友评论