-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathrequest.go
71 lines (62 loc) · 1.65 KB
/
request.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
package wiki
import (
"crypto/tls"
"encoding/json"
"fmt"
"net/http"
"net/url"
"strings"
)
// Request sets up the request against the api with the correct parameters
// and has functionality to fetch the data and convert it to a response.
type Request struct {
*url.URL
}
// NewRequest creates a new request against baseURL for language.
// Language is interpolated in the baseURL if asked, if not it is ignored.
// Query is the title of the page to fetch.
// Returns an error if the URL can not be parsed.
func NewRequest(baseURL, query, language string) (*Request, error) {
if strings.Contains(baseURL, "%s") {
baseURL = fmt.Sprintf(baseURL, language)
}
url, err := url.Parse(baseURL)
if err != nil {
return nil, err
}
v := url.Query()
v.Set("action", "query")
v.Set("prop", "extracts|info")
v.Set("format", "json")
v.Set("exintro", "")
v.Set("explaintext", "")
v.Set("inprop", "url")
v.Set("redirects", "")
v.Set("converttitles", "")
v.Set("titles", query)
url.RawQuery = v.Encode()
return &Request{url}, nil
}
// Execute fetches the data and decodes it into a Response.
// Returns an error if the data could not be retrieved or the decoding fails.
func (r *Request) Execute(noCheckCert bool) (*Response, error) {
client := &http.Client{}
if noCheckCert {
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, //nolint:gosec
}
client = &http.Client{Transport: tr}
}
response, err := client.Get(r.String())
if err != nil {
return nil, err
}
defer response.Body.Close()
d := json.NewDecoder(response.Body)
resp := &Response{}
err = d.Decode(resp)
if err != nil {
return nil, err
}
return resp, nil
}