This repository has been archived by the owner on Jul 29, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
99 lines (83 loc) · 2.07 KB
/
client.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
package gotanking
import (
"errors"
"net/http"
"time"
)
const (
// BaseURL of the API
BaseURL string = "https://api.worldoftanks.com/wot/"
// DefaultClientTimeout defines the client timeout value
DefaultClientTimeout time.Duration = 5 * time.Second
)
var (
// ErrNilApplicationID is raised when the client is instantiated without an API key
ErrNilApplicationID error = errors.New("Application ID cannot be nil")
)
// Option is the function definition for functions overriding defaults
type Option func(*WOTClient) error
// WOTClient is the object to interface with the API
type WOTClient struct {
client *http.Client
ApplicationID string
baseURL string
realm string
}
// NewClient returns a pointer to a new client object
func NewClient(appID string, opts ...Option) (*WOTClient, error) {
c := &WOTClient{
client: &http.Client{
Timeout: DefaultClientTimeout,
},
ApplicationID: appID,
baseURL: BaseURL,
realm: "na",
}
if err := c.parseOpts(opts...); err != nil {
return nil, err
}
if c.ApplicationID == "" {
return nil, ErrNilApplicationID
}
return c, nil
}
// parseOpts overrides instantiated defaults
func (c *WOTClient) parseOpts(opts ...Option) error {
// range over each option (function)
// overriding defaults in sequence
for _, option := range opts {
err := option(c)
if err != nil {
return err
}
}
return nil
}
// SetBaseURL sets the URL irrespective of the realm. This is used for testing against a test server.
func SetBaseURL(url string) Option {
return func(c *WOTClient) error {
c.baseURL = url
return nil
}
}
// SetRealm sets the API endpoint to other realms
func SetRealm(realm string) Option {
var url string
switch realm {
case "na":
url = "https://api.worldoftanks.com/wot/"
case "eu":
url = "https://api.worldoftanks.eu/wot/"
case "ru":
url = "https://api.worldoftanks.ru/wot/"
case "asia":
url = "https://api.worldoftanks.asia/wot/"
default:
url = "https://api.worldoftanks.com/wot/"
}
return func(c *WOTClient) error {
c.baseURL = url
c.realm = realm
return nil
}
}