-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexchangerate.go
More file actions
81 lines (72 loc) · 2.2 KB
/
exchangerate.go
File metadata and controls
81 lines (72 loc) · 2.2 KB
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
package exchangerate
import (
"errors"
"net/url"
"os"
)
var apiURL *url.URL
var (
ErrUnknownResponse error = errors.New("unknown exchangerate API response")
ErrNoAPIKey error = errors.New("exchangerate API key is not set")
ErrInvalidAPIKey error = errors.New("exchangerate API key is invalid")
ErrUnverifiedAccount error = errors.New("exchangerate account not verified")
ErrQuotaReached error = errors.New("exchangerate account quota reached")
ErrMalformedRequest error = errors.New("malformed request for exchangerate API")
ErrUnsupportedCurrency error = errors.New("unsupported currency for exchangerate API")
ErrFromCurrencyIsNil error = errors.New("from currency is nil")
ErrToCurrencyIsNil error = errors.New("to currency is nil")
)
type baseAPIResponse struct {
Result string `json:"result"`
Documentation string `json:"documentation"`
TermsOfUse string `json:"terms_of_use"`
ErrorType string `json:"error-type"`
}
func (response *baseAPIResponse) Verify() error {
switch response.Result {
case "success":
return nil
case "error":
switch response.ErrorType {
case "invalid-key":
return ErrInvalidAPIKey
case "inactive-account":
return ErrUnverifiedAccount
case "quota-reached":
return ErrQuotaReached
case "unsupported-code":
return ErrUnsupportedCurrency
case "malformed-request":
return ErrMalformedRequest
}
}
return ErrUnknownResponse
}
type baseUpdateAPIResponse struct {
baseAPIResponse
TimeLastUpdateUnix int64 `json:"time_last_update_unix"`
TimeLastUpdateUTC string `json:"time_last_update_utc"`
TimeNextUpdateUnix int64 `json:"time_next_update_unix"`
TimeNextUpdateUTC string `json:"time_next_update_utc"`
}
func initURL() error {
var errParse error
apiURL, errParse = url.Parse(`https://v6.exchangerate-api.com/v6/`)
if errParse != nil {
return errParse
}
apiKey, apiKeySet := os.LookupEnv("EXCHANGERATE_API_KEY")
if !apiKeySet {
return ErrNoAPIKey
}
apiURL = apiURL.JoinPath(apiKey)
return nil
}
func init() {
if errURL := initURL(); errURL != nil {
panic(errURL)
}
if errSupportedCurrencies := initSupportedCurrencies(); errSupportedCurrencies != nil {
panic(errSupportedCurrencies)
}
}