-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.go
92 lines (74 loc) · 2.09 KB
/
api.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
//
// go-crypto-market-ui
// Command-line utility to track cryptocurrencies in realtime.
//
// Copyright 2020-2024, Marc S. Brooks (https://mbrooks.info)
// Licensed under the MIT license:
// http://www.opensource.org/licenses/mit-license.php
//
package lib
import (
"strings"
"github.com/nuxy/go-crypto-market-ui/lib/common"
"github.com/nuxy/go-crypto-market-ui/lib/service"
)
// API declared data types.
type API struct {
Config *Config
endpointName string
}
// NewAPI creates a new service instance.
func NewAPI(config *Config, endpointName string) *API {
api := &API{}
api.Config = config
api.endpointName = endpointName
return api
}
// URL returns as constructed location.
func (api *API) URL() string {
return api.serviceInterface().URL(api.endpointName) + "?" + api.params()
}
// Parse returns API response body data.
func (api *API) Parse(body []byte) interface{} {
return api.serviceInterface().Parse(api.endpointName, body)
}
// Returns the endpoint query parameters.
func (api *API) params() string {
values := api.serviceInterface().Params(api.endpointName)
params := make([]string, len(values))
for i, v := range values {
field := strings.Split(v, "=")
switch field[1] {
case "{APIKey}":
params[i] = field[0] + "=" + api.Config.APIKey()
case "{Currency}":
params[i] = field[0] + "=" + api.Config.Currency()
case "{Language}":
params[i] = field[0] + "=" + api.Config.Language()
case "{Symbols}":
params[i] = field[0] + "=" + api.symbols()
default:
params[i] = field[0] + "=" + field[1]
}
}
return strings.Join(params, "&")
}
// Returns config defined Symbols.
func (api *API) symbols() string {
items := api.Config.Symbols()
values := make([]string, 0, len(items))
for k := range items {
values = append(values, k)
}
return strings.Join(values, ",")
}
// Assigns runtime selected interface.
func (api *API) serviceInterface() common.ServiceInterface {
var instance common.ServiceInterface
// TODO: Support multiple services.
switch api.Config.ServiceName() {
case "CoinMarketCap":
instance = (service.CoinMarketCap{})
}
return instance
}