-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
111 lines (89 loc) · 2.36 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
100
101
102
103
104
105
106
107
108
109
110
111
package alchemyapi
import (
"encoding/json"
"io"
"io/ioutil"
"net/http"
"net/url"
"strings"
)
// Client implements a AlchemyAPI client.
type Client struct {
*Config
}
type Entity struct {
Type string `json:"type"`
Relevance string `json:"relevance"`
Count string `json:"count"`
Text string `json:"text"`
Disambiguated Disambiguated `json:"disambiguated"`
}
type Disambiguated struct {
SubType []string `json:"subType"`
Name string `json:"name"`
DBpedia string `json:"dbpedia"`
Yago string `json:"yago"`
OpenCyc string `json:"opencyc"`
Umbel string `json:"umbel"`
MusicBrainz string `json:"musicBrainz"`
Freebase string `json:"freebase"`
Website string `json:"website"`
}
type Output struct {
Status string `json:"status"`
StatusInfo string `json:"statusInfo"`
WarningMessage string `json:"warningMessage"`
Usage string `json:"usage"`
URL string `json:"url"`
}
// New client.
func New(config *Config) *Client {
c := &Client{Config: config}
return c
}
// call rpc style endpoint.
func (c *Client) call(path string, in map[string]string) (io.ReadCloser, error) {
query := url.Values{}
query.Set("apikey", c.APIKey)
query.Set("outputMode", "json")
u := "http://gateway-a.watsonplatform.net/calls" + path + "?" + query.Encode()
form := url.Values{}
for key, value := range in {
form.Add(key, value)
}
req, err := http.NewRequest("POST", u, strings.NewReader(form.Encode()))
if err != nil {
return nil, err
}
req.PostForm = form
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
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
}