This repository has been archived by the owner on Sep 8, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
coinmarketcap.go
executable file
·103 lines (92 loc) · 2.48 KB
/
coinmarketcap.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
// Package coinmarketcap is an API Client for CMC Pro
package coinmarketcap
import (
"encoding/json"
"fmt"
"net/http"
"os"
"strings"
"sync"
"github.com/hexoul/go-coinmarketcap/types"
"github.com/hexoul/go-coinmarketcap/util"
)
// Interface for APIs
type Interface interface {
CryptoInfo(options *types.Options) (*types.CryptoInfoMap, error)
CryptoMap(options *types.Options) (*types.CryptoMapList, error)
CryptoListingsLatest(options *types.Options) (*types.CryptoMarketList, error)
CryptoMarketPairsLatest(options *types.Options) (*types.MarketPairs, error)
CryptoOhlcvLatest(options *types.Options) (*types.OhlcvMap, error)
CryptoOhlcvHistorical(options *types.Options) (*types.OhlcvList, error)
CryptoMarketQuotesLatest(options *types.Options) (*types.CryptoMarketMap, error)
ExchangeInfo(options *types.Options) (*types.ExchangeInfoMap, error)
ExchangeMap(options *types.Options) (*types.ExchangeMapList, error)
ExchangeListingsLatest(options *types.Options) (*types.ExchangeMarketList, error)
ExchangeMarketPairsLatest(options *types.Options) (*types.MarketPairs, error)
ExchangeMarketQuotesLatest(options *types.Options) (*types.ExchangeMarketQuotes, error)
}
// Client for CoinMarketCap API
type Client struct {
proAPIKey string
}
var (
instance *Client
once sync.Once
apiKey string
)
const (
baseURL = "https://pro-api.coinmarketcap.com/v1"
)
func init() {
for _, val := range os.Args {
arg := strings.Split(val, "=")
if len(arg) < 2 {
continue
} else if arg[0] == "-cmcApikey" {
apiKey = arg[1]
}
}
}
// GetInstance returns singleton
func GetInstance() *Client {
once.Do(func() {
if apiKey == "" {
panic("API KEY REQUIRED")
}
instance = &Client{
proAPIKey: apiKey,
}
})
return instance
}
// GetInstanceWithKey returns singleton
func GetInstanceWithKey(key string) *Client {
once.Do(func() {
if key == "" {
panic("API KEY REQUIRED")
}
instance = &Client{
proAPIKey: key,
}
})
return instance
}
func (s *Client) getResponse(url string) (*types.Response, []byte, error) {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, nil, err
}
req.Header.Add("X-CMC_PRO_API_KEY", s.proAPIKey)
body, err := util.DoReq(req)
if err != nil {
return nil, nil, err
}
resp := new(types.Response)
if err := json.Unmarshal(body, &resp); err != nil {
return nil, nil, err
}
if resp.Status.ErrorCode != 0 {
return nil, nil, fmt.Errorf("[%d] %s", resp.Status.ErrorCode, *resp.Status.ErrorMessage)
}
return resp, body, nil
}