在Go中查找地址的BTC余额

时间:2016-02-22 10:48:16

标签: go

我需要纠正和转换一个函数,检查btc balance的2个地址,比如(addr和addr1),返回的是json值,我需要指定我不太了解golang ..需要帮助!< / p>

func balance(addr) {
    var url = "https://bitcoin.toshi.io/api/v0/addresses/" + addr
    response, _ := http.Get(url)
    defer response.Body.Close()
    contents, _ := ioutil.ReadAll(response.Body)
    return contents
}

编辑:

我需要一个函数来获取2个btc地址的余额,或者使用这个库btcwallet

func GetAddressBalance(icmd btcjson.Cmd) (interface{}, *btcjson.Error) 
func GetAddressesByAccount(icmd btcjson.Cmd) (interface{}, *btcjson.Error) 
func GetBalance(icmd btcjson.Cmd) (interface{}, *btcjson.Error) 

1 个答案:

答案 0 :(得分:0)

你走在正确的轨道上。 api返回一个json。这可以解组成结构(Address)。这样你就可以访问api返回的所有内容。不要忘记始终检查错误代码!将some_address替换为实际地址以获得余额。

package main

import (
    "encoding/json"
    "fmt"
    "net/http"
)

func main() {
    a, err := getAddress("some_address")
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println("Balance:", a.Balance)
}

type Address struct {
    Hash                string
    Balance             int
    Received            int
    Send                int
    UnconfirmedBalance  int `json:"unconfirmed_balance"`
    UnconfirmedReceived int `json:"unconfirmed_received"`
    UnconfirmedSent     int `json:"unconfirmed_sent"`
}

func getAddress(addr string) (*Address, error) {
    resp, err := http.Get("https://bitcoin.toshi.io/api/v0/addresses/" + addr)
    if err != nil {
        return nil, err
    }
    defer resp.Body.Close()

    if resp.StatusCode != http.StatusOK {
        return nil, fmt.Errorf("Error: %v", http.StatusText(resp.StatusCode))
    }

    var address Address
    decoder := json.NewDecoder(resp.Body)
    if err := decoder.Decode(&address); err != nil {
        return nil, err
    }

    return &address, nil
}