Json-RPC操作Ethereum 节点

准备工作
本地搭建以太坊私链,使用POA共识。节点开启IPC。
功能描述
试过一些rpc包和go-ethereum 的rpc包,都不是很好用。有些命令好使,有些就报错。没有去深究这些rpc包生成的json有什么异常。直接自己实现。实现其实很简单,而且用起来也更靠谱。
上码
package eth

import (
“bytes”
“io/ioutil”
“net/http”
)

type ethRequest struct {
general
Method string `json:”method”`
Params []interface{} `json:”params”`
}

type general struct {
JsonRPC string `json:”jsonrpc”`
ID int `json:”id”`
}

//生成ethRequest,Marshal 成[]byte ,传入do函数即可操作ethereum 节点
func do(jsonParam []byte)([]byte,error){
reader := bytes.NewReader(jsonParam)
url := “http://127.0.0.1:8545”
request, err := http.NewRequest(“POST”, url, reader)
if err != nil {
return []byte(“”),err
}
request.Header.Set(“Content-Type”, “application/json;charset=UTF-8”)
client := http.Client{}
resp, err := client.Do(request)
if err != nil {
return []byte(“”),err
}
respBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return []byte(“”),err
}
return respBytes,nil
}
其他说明
了解更多以太坊管理命令所需要的参数。Here: https://github.com/ethereum/g…

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理