-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
80 lines (63 loc) · 1.41 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
package wikidata
import (
"encoding/json"
"io"
"io/ioutil"
"net/http"
"net/url"
"strings"
)
// Client implements a WikiData client.
type Client struct {
*Config
}
// New client.
func New(config *Config) *Client {
c := &Client{Config: config}
return c
}
// call rpc style endpoint.
func (c *Client) call(action string, in map[string]string) (io.ReadCloser, error) {
baseUrl := "https://www.wikidata.org/w/api.php"
query := url.Values{}
query.Set("action", action)
query.Set("format", "json")
query.Set("languages", "en")
for key, value := range in {
query.Set(key, value)
}
url := baseUrl + "?" + query.Encode()
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
r, _, err := c.do(req)
return r, err
}
// perform the request.
func (c *Client) do(req *http.Request) (io.ReadCloser, int64, error) {
res, err := c.HTTPClient.Do(req)
if err != nil {
return nil, 0, err
}
if res.StatusCode < 400 {
return res.Body, res.ContentLength, err
}
defer res.Body.Close()
e := &Error{
Status: http.StatusText(res.StatusCode),
StatusCode: res.StatusCode,
}
kind := res.Header.Get("Content-Type")
if strings.Contains(kind, "text/plain") {
if b, err := ioutil.ReadAll(res.Body); err == nil {
e.Summary = string(b)
return nil, 0, e
}
return nil, 0, err
}
if err := json.NewDecoder(res.Body).Decode(e); err != nil {
return nil, 0, err
}
return nil, 0, e
}