-
Notifications
You must be signed in to change notification settings - Fork 57
/
main.go
180 lines (148 loc) · 3.65 KB
/
main.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
package tmdb
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"time"
)
const baseURL string = "https://api.themoviedb.org/3"
const maxRequestPerSecond = 4
var (
// hack: add some millisecond for don`t get 429 error
rate = time.Second/maxRequestPerSecond + time.Millisecond*20
throttle = time.Tick(rate)
)
// Config struct
type Config struct {
APIKey string
UseProxy bool
Proxies []Proxy
}
// Proxy struct
type Proxy struct {
Host string
Port string
Login string
Password string
Auth bool
throttle <-chan time.Time
}
// TMDb container struct for global properties
type TMDb struct {
apiKey string
}
var internalConfig tmdbConfig
type tmdbConfig struct {
useProxy bool
proxies []Proxy
roundRobin RoundRobin
}
type apiStatus struct {
Code int `json:"status_code"`
Message string `json:"status_message"`
}
// Init setup the apiKey
func Init(config Config) *TMDb {
internalConfig := new(tmdbConfig)
if config.UseProxy == true && len(config.Proxies) > 1 {
internalConfig.useProxy = config.UseProxy
internalConfig.proxies = prepareProxies(config.Proxies)
internalConfig.roundRobin = InitRoundRobin(len(internalConfig.proxies))
}
return &TMDb{apiKey: config.APIKey}
}
// ToJSON converts from struct to JSON
func ToJSON(payload interface{}) (string, error) {
jsonRes := []byte("{}") // Default value in case of error
jsonRes, err := json.MarshalIndent(payload, "", " ")
return string(jsonRes), err
}
func getTmdb(url string, payload interface{}) (interface{}, error) {
var httpRequest http.Client
var blocker <-chan time.Time
if internalConfig.useProxy {
roundRobin := internalConfig.roundRobin.GetTicker()
proxy := internalConfig.proxies[roundRobin]
if proxy.Host == "localhost" {
httpRequest = getHTTPClient()
} else {
httpRequest = getHTTPClientWithProxy(proxy)
}
blocker = proxy.throttle
} else {
httpRequest = getHTTPClient()
blocker = throttle
}
<-blocker
res, err := httpRequest.Get(url)
if err != nil { // HTTP connection error
return payload, err
}
defer res.Body.Close() // Clean up
body, err := ioutil.ReadAll(res.Body)
if err != nil { // Failed to read body
return payload, err
}
if res.StatusCode >= 200 && res.StatusCode < 300 { // Success!
json.Unmarshal(body, &payload)
return payload, nil
}
// Handle failure modes
var status apiStatus
err = json.Unmarshal(body, &status)
if err != nil {
return payload, err
}
return payload, fmt.Errorf("Code (%d): %s", status.Code, status.Message)
}
func getOptionsString(options map[string]string, availableOptions map[string]struct{}) string {
var optionsString = ""
for key, val := range options {
if _, ok := availableOptions[key]; ok {
newString := fmt.Sprintf("%s&%s=%s", optionsString, key, val)
optionsString = newString
}
}
return optionsString
}
func prepareProxies(proxies []Proxy) []Proxy {
preparedProxies := make([]Proxy, len(proxies))
for i, proxy := range proxies {
proxy.throttle = time.Tick(rate)
preparedProxies[i] = proxy
}
return preparedProxies
}
func getHTTPClient() http.Client {
return http.Client{
Transport: &http.Transport{},
}
}
func getHTTPClientWithProxy(proxy Proxy) http.Client {
return http.Client{
Transport: &http.Transport{
Proxy: http.ProxyURL(makeProxyURL(proxy)),
},
}
}
func makeProxyURL(proxy Proxy) *url.URL {
proxyURL := ""
if proxy.Auth {
proxyURL = fmt.Sprintf("https://%s:%s@%s:%s",
proxy.Login,
proxy.Password,
proxy.Host,
proxy.Port)
} else {
proxyURL = fmt.Sprintf("https://%s:%s",
proxy.Host,
proxy.Port)
}
proxyURLInterface, err := url.Parse(proxyURL)
if err != nil {
panic(err)
}
return proxyURLInterface
}