The go language has many advantages, such as easy to learn, powerful, cross-platform compilation, and so on, so choose to go into Ethereum.
The following environments are required before you begin:
- Ubuntu (take ubuntu16.04 for example)
Geth
Ubuntu16.04 installation Go1.9.2
Before interacting with Ethereum, we need to install the Go Language development tool, the version chosen here is Go1.9.2. Next we start installing
Enter the following command at the terminal
$ curl -O https://storage.googleapis.com/golang/go1.9.linux-amd64.tar.gz $ tar -C /usr/local -zxvf go1.9.linux-amd64.tar.gz $ mkdir -p ~/go/src$ export GOPATH=~/go/src //go项目要放到~/go/src目录下编译$ go version
Next, you need to use the IPC mode and RPC mode. Go-ethereum has the relevant files and tools, we clone it down.
Clone Go-ethereum to Local
In the terminal input
$ cd ~/go/src$ mkdir -p github.com/ethereum$ cd github.com/ethereum/$ git clone https://github.com/ethereum/go-ethereum.git
Deploy smart Contracts to Geth
The next operation requires the Geth private node, the following is the startup command and parameters
$ geth --identity "pdj" --datadir data0 --rpcport 8545 --rpccorsdomain "*" --port "30303" --nodiscover --nat "any" --networkid 15 --rpc --rpcapi "db,eth,net,web3,personal" --ipcpath "geth.ipc" console
- Compiling the smart contract on http://remix.ethereum.org/
- Select "Web3 Provider" in the Remix Run option, Web3 Provider Endpoint as "http://localhost:8545"
IPC Mode call Smart Contract
- Copy the ABI generated when deploying the smart contract into an. abi file
- Generate the. Go file with the Abigen tool
Here you need to compile and generate a Abigen tool to generate the. Go file
- Compiling main.go under the ~/go/src/github.com/ethereum/go-ethereum/cmd/abigen/directory
$ cd ~/go/src/github.com/ethereum/go-ethereum/cmd/abigen/$ go build -i
After the compilation is successful, the Abigen is generated in the current directory.
$ abigen --abi xx.abi --pkg pkgname --type apiname --out xx.go1. abi 文件在 remix 部署时可以得到2. Pkg 指定的是编译成的 go 文件对应的 package 名称3. type指定的是go文件的入口函数,可以认为是类名4. out 指定输出go文件名称
Go Call RPC Interface
- Geth start with parameter--rpcapi "Db,eth,net,web3,personal"
- Go call GetBalance () instance
package mainimport ( "fmt" "github.com/ethereum/go-ethereum/rpc")func main() { client, err := rpc.Dial("http://localhost:8545") if err != nil { fmt.Println("rpc.Dial err", err) return } var account[]string err = client.Call(&account, "eth_accounts") var result string //var result hexutil.Big err = client.Call(&result, "eth_getBalance", account[0], "latest") //err = ec.c.CallContext(ctx, &result, "eth_getBalance", account, "latest") if err != nil { fmt.Println("client.Call err", err) return } fmt.Printf("account[0]: %s\nbalance[0]: %s\n", account[0], result) //fmt.Printf("accounts: %s\n", account[0])}