繼昨天說完Elrond Hyper block的內容後,要開始來寫呼叫函式,在這之前必須先優化一下json那邊的寫法,主要是ioutil.ReadAll可能會有檔案越大消能越差甚至可能撐爆記憶體的風險,所以這邊來改寫一下,
原先是
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
}
}(resp.Body)
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// handle error
}
fmt.Println(string(body))
err = json.Unmarshal(body, &model)
if err != nil {
return
}
使用json的Decoder來處理
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
}
}(resp.Body)
decoder := json.NewDecoder(resp.Body)
err = decoder.Decode(&model)
if err != nil {
return
}
執行一下確認運行正常,
新增hyperblock的model,model/hyperblockRes.go
package model
type HyperBlockRes struct {
Code string `json:"code"`
Data HyperBlockInfo `json:"data"`
}
type HyperBlockInfo struct {
HyperBLock HyperBLock `json:"hyperblock"`
}
type HyperBLock struct {
Hash string `json:"hash"`
PrevBlockHash string `json:"prevBlockHash"`
StateRootHash string `json:"stateRootHash"`
Nonce int `json:"nonce"`
Round int `json:"round"`
Epoch int `json:"epoch"`
NumTxs int `json:"numTxs"`
AccumulatedFees string `json:"accumulatedFees"`
DeveloperFees string `json:"developerFees"`
AccumulatedFeesInEpoch string `json:"accumulatedFeesInEpoch"`
DeveloperFeesInEpoch string `json:"developerFeesInEpoch"`
Timestamp int `json:"timestamp"`
ShardBlocks []ShardBlock `json:"shardBlocks"`
Transactions []Transaction `json:"transactions"`
Status string `json:"status"`
}
type ShardBlock struct {
Hash string `json:"hash"`
Nonce int `json:"nonce"`
Round int `json:"round"`
Shard int `json:"shard"`
}
type Transaction struct {
Type string `json:"type"`
ProcessingTypeOnSource string `json:"processingTypeOnSource"`
ProcessingTypeOnDestination string `json:"processingTypeOnDestination"`
Hash string `json:"hash"`
Nonce int `json:"nonce"`
Round int `json:"round"`
Epoch int `json:"epoch"`
Value string `json:"value"`
Receiver string `json:"receiver"`
Sender string `json:"sender"`
GasPrice int `json:"gasPrice"`
Data string `json:"data"`
PreviousTransactionHash string `json:"previousTransactionHash"`
OriginalTransactionHash string `json:"originalTransactionHash"`
SourceShard int `json:"sourceShard"`
DestinationShard int `json:"destinationShard"`
MiniblockType string `json:"miniblockType"`
MiniblockHash string `json:"miniblockHash"`
Status string `json:"status"`
Tokens []string `json:"tokens"`
EsdtValues []string `json:"esdtValues"`
Operation string `json:"operation"`
InitiallyPaidFee string `json:"initiallyPaidFee"`
}
然後在nodeUtils.go 新增GetHyperBlock
func GetHyperBlock(nonce string) {
var hyperBlockRes model.HyperBlockRes
utils.HttpGet(url+"/hyperblock/by-nonce/"+nonce+"?withTxs=true", &hyperBlockRes)
fmt.Println(hyperBlockRes)
fmt.Printf("transactions: %d\n", hyperBlockRes)
}
執行一下看結果,確認有存取到hyperblock了。
nodeUtils.GetHyperBlock("1131724")