今天預計要完成呼叫Elrond node API的部分
package internal
import (
"fmt"
"io"
"io/ioutil"
"net/http"
)
func HttpGet(url string) []byte {
resp, err := http.Get(url)
if err != nil {
// handle error
}
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))
return body
}
因為這是取得錢包餘額所以function新增在原本的walletUtils.go,在取得http的response時需要先定義好response的結構
我們先看一下api回傳的結構
{
"data": {
"balance": "26943172500000000000",
"blockInfo": {
"nonce": 1895345,
"hash": "61251b1aeb8a7e95d1a967cdde5b8d909acba31a5d0610c2892a808f7405bd4b",
"rootHash": "895573e116c6897fe9cbd2474b972551b9570ecee42e2f7361e98d129a35b54f"
}
},
"code": "successful"
}
然後定義好struct
type BalanceRes struct {
Code string `json:"code"`
Data BalanceResData `json:"data"`
}
type BalanceResData struct {
Balance string `json:"balance"`
BlockInfo BalanceResDataInfo `json:"blockInfo"`
}
type BalanceResDataInfo struct {
Nonce int `json:"nonce"`
Hash string `json:"hash"`
RootHash string `json:"rootHash"`
}
再來就是撰寫呼叫的function
func GetAddressBalance(address string) {
url := conf.Get("server.url").(string)
body := utils.HttpGet(url + "/address/" + address + "/balance")
var balanceRes BalanceRes
err := json.Unmarshal(body, &balanceRes)
if err != nil {
return
}
fmt.Println(balanceRes)
fmt.Printf("balance: %s\n", balanceRes.Data.Balance)
}
執行的結果
成功取得api回傳的balance了,明天還需要新增其他的api。