This repository was archived by the owner on Aug 4, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
234 lines (190 loc) · 4.84 KB
/
client.go
File metadata and controls
234 lines (190 loc) · 4.84 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
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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
package bingo
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"strings"
"time"
"dev.freespoke.com/bingo/v2/bingtypes"
)
const (
authHeaderName = "Ocp-Apim-Subscription-Key"
defaultUserAgent = "FreedomFries (Bingo v1.0)"
)
type client struct {
HTTP *http.Client
APIKey string
UserAgent string
}
type requestOpts interface {
toQueryString(v *url.Values)
toHeader(userAgent string, h *http.Header)
}
func (c *client) makeGetRequest(
ctx context.Context,
baseURL string,
path string,
opts requestOpts,
) (*http.Request, error) {
requestURL := fmt.Sprintf("%s/%s",
strings.TrimRight(baseURL, "/"),
strings.TrimLeft(path, "/"),
)
u, err := url.Parse(requestURL)
if err != nil {
return nil, err
}
q := u.Query()
opts.toQueryString(&q)
u.RawQuery = encodeBingParams(q)
headers := http.Header{}
opts.toHeader(c.UserAgent, &headers)
req, err := http.NewRequestWithContext(ctx, "GET", u.String(), nil)
if err != nil {
return nil, err
}
req.Header = headers
return req, nil
}
func (c *client) sendRequest(req *http.Request, params RequestParams) (*http.Response, error) {
req.Header.Set("Accept", "application/json")
req.Header.Set(authHeaderName, c.APIKey)
ua := params.UserAgent
if ua == "" {
ua = defaultUserAgent
}
req.Header.Set("User-Agent", ua)
res, err := c.HTTP.Do(req)
if err != nil {
return res, err
}
var e bingtypes.ErrorResponse
if res.StatusCode == 404 || res.StatusCode == 401 {
e.Err = res.Status
return res, e
} else if res.StatusCode >= 400 {
err = json.NewDecoder(res.Body).Decode(&e)
if err != nil {
return res, err
}
return res, e
}
return res, nil
}
func (c *client) getResponseMetadata(res *http.Response) *bingtypes.ResponseMetadata {
return &bingtypes.ResponseMetadata{
Market: res.Header.Get("BingAPIs-Market"),
TraceID: res.Header.Get("BingAPIs-TraceId"),
RetryAfter: res.Header.Get("Retry-After"),
ClientID: res.Header.Get("x-MSEdge-ClientID"),
}
}
type RequestParams struct {
CountryCode string
Count int
Market string
Offset int
SafeSearch string
SetLang string
freshness string
TextDecorations bool
TextFormat string
// UserAgent may be specified if you do not wish to use the default client
// library UA. If set, this should be a pass-through from the requesting
// end user. Bing may serve different responses better tailored for the user
// (e.g. mobile-optimized sites).
UserAgent string
}
func (o *RequestParams) WithFreshness(f bingtypes.Freshness) {
o.freshness = f.String()
}
func (o *RequestParams) WithCustomFreshness(start, end *time.Time) {
if start == nil || start.IsZero() {
return
}
o.freshness = start.Format("2006-01-02")
if end != nil && !end.IsZero() {
o.freshness = fmt.Sprintf("%s..%s", start.Format("2006-01-02"), end.Format("2006-01-02"))
}
}
func (o RequestParams) toQueryString(v *url.Values) {
if o.CountryCode != "" {
v.Add("cc", o.CountryCode)
}
if o.Count != 0 {
v.Add("count", fmt.Sprint(o.Count))
}
v.Add("offset", fmt.Sprint(o.Offset))
if o.Market != "" {
v.Add("mkt", o.Market)
}
if o.SafeSearch != "" {
v.Add("safeSearch", o.SafeSearch)
}
if o.SetLang != "" {
v.Add("setLang", o.SetLang)
} else if o.Market != "" {
v.Add("setLang", o.Market)
}
if o.freshness != "" {
v.Add("freshness", o.freshness)
}
if o.TextDecorations {
v.Add("textDecorations", "true")
}
if o.TextFormat != "" {
v.Add("textFormat", o.TextFormat)
}
}
type RequestHeaders struct {
AcceptLanguage []string
Pragma string
ClientID string
ClientIP string
SearchLocation map[string]string
}
func (o RequestHeaders) toHeader(userAgent string, h *http.Header) {
if len(o.AcceptLanguage) != 0 {
h.Add("Accept-Language", strings.Join(o.AcceptLanguage, ","))
}
if o.ClientID != "" {
h.Add("X-MSEdge-ClientID", o.ClientID)
}
if o.ClientIP != "" {
h.Add("X-MSEdge-ClientIP", o.ClientIP)
}
if len(o.SearchLocation) > 0 {
var loc []string
for k, v := range o.SearchLocation {
loc = append(loc, fmt.Sprintf(
"%s:%s",
k,
v,
))
}
h.Add("X-Search-Location", strings.Join(loc, ";"))
}
if o.Pragma != "" {
h.Add("Pragma", o.Pragma)
}
h.Add("User-Agent", userAgent)
}
func makeBaseURL(baseURL string, path string) string {
return fmt.Sprintf("%s/%s", strings.TrimRight(baseURL, "/"), strings.TrimLeft(path, "/"))
}
// encodingBingParams fixes query encoding for Bing which isn't fully standards compliant.
// Bing blows up if responseFilter has commas urlencoded as %2C.
// These need to be put back to the original, unencoded commas.
func encodeBingParams(v url.Values) string {
for k := range v {
if strings.ToLower(k) == "responsefilter" {
f := url.QueryEscape(v.Get(k))
v.Del(k)
res := v.Encode() + "&" + k + "=" + strings.ReplaceAll(f, "%2C", ",")
return res
}
}
return v.Encode()
}