-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathblockchain.go
86 lines (70 loc) · 1.49 KB
/
blockchain.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package blockchain
import (
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"reflect"
)
const (
rootURL = "https://blockchain.info"
)
var (
// Used when an iterator has exhausted its supply.
IterDone = errors.New("iterator done")
)
type BlockChain struct {
client *http.Client
GUID string
Password string
SecondPassword string
APICode string
}
type Item interface {
load(bc *BlockChain) error
}
func New(c *http.Client) *BlockChain {
return &BlockChain{client: c}
}
func checkHTTPResponse(r *http.Response) error {
if r.StatusCode == 200 {
return nil
}
bodyErr, err := ioutil.ReadAll(r.Body)
if err != nil {
return err
}
return fmt.Errorf("%s: %s: %.30q...",
r.Request.URL, r.Status, bodyErr)
}
func (bc *BlockChain) Request(item Item) error {
return item.load(bc)
}
func (bc *BlockChain) httpGetJSON(url string, v interface{}) error {
resp, err := bc.client.Get(url)
if err != nil {
return err
}
if err := checkHTTPResponse(resp); err != nil {
return err
}
defer resp.Body.Close()
return decodeJSON(resp.Body, v)
}
func decodeJSON(r io.Reader, v interface{}) error {
data, err := ioutil.ReadAll(r)
if err != nil {
return err
}
if err := json.Unmarshal(data, v); err != nil {
return fmt.Errorf("%s with data %.30q...", err.Error(), data)
}
// Check for errors.
errVal := reflect.ValueOf(v).Elem().FieldByName("Error")
if errVal.IsValid() && errVal.String() != "" {
return errors.New(errVal.String())
}
return nil
}