-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.go
102 lines (81 loc) · 1.85 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
93
94
95
96
97
98
99
100
101
102
package currconv
import (
"encoding/json"
"errors"
"io"
"net/http"
"net/url"
)
// Config of the API.
type Config struct {
BaseURL string
Version string
APIKey string
}
// API is the wrapper implementation of CurrencyConverterAPI.
type API struct {
config Config
}
type Error struct {
Status int `json:"status"`
Error string `json:"error"`
}
// NewAPI create and return an API.
func NewAPI(config Config) *API {
return &API{
config,
}
}
type response interface {
Convert | ConvertCompact | ConvertHistorical | ConvertHistoricalCompact | Currency | Country | Usage
}
// call is a function used by all APIs to request CurrencyConverterAPI.
// This function will execute `handler` which consist unique logic from the caller.
func call[T response](a *API, shouldPrefixAPIPath bool, path string, handler func(q url.Values) error) (result *T, err error) {
u, err := url.Parse(a.config.BaseURL)
if err != nil {
return nil, err
}
if shouldPrefixAPIPath {
u = u.JoinPath("api").JoinPath(a.config.Version)
}
u = u.JoinPath(path)
query := u.Query()
query.Add("apiKey", a.config.APIKey)
err = handler(query)
if err != nil {
return nil, err
}
u.RawQuery = query.Encode()
resp, err := http.Get(u.String())
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, parseError(resp)
}
body, err := io.ReadAll(resp.Body)
defer resp.Body.Close()
if err != nil {
return nil, err
}
err = json.Unmarshal(body, &result)
if err != nil {
return nil, err
}
return
}
// parseError uses `json.Unmarshal` to returns Error whenever it is possible.
func parseError(resp *http.Response) error {
body, err := io.ReadAll(resp.Body)
defer resp.Body.Close()
if err != nil {
return err
}
e := Error{}
err = json.Unmarshal(body, &e)
if err != nil {
return errors.New(string(body))
}
return errors.New(e.Error)
}