-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
103 lines (75 loc) · 2.14 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
package thesaurus
import (
"encoding/json"
"io/ioutil"
"net/http"
"net/url"
"github.com/Rican7/define/source"
)
const (
// baseURLString is the base URL for all Oxford API interactions
baseURLString = "https://od-api.oxforddictionaries.com/api/v2/"
entriesURLString = baseURLString + "thesaurus/"
httpRequestAcceptHeaderName = "Accept"
httpRequestAppIDHeaderName = "app_id"
httpRequestAppKeyHeaderName = "app_key"
jsonMIMEType = "application/json"
)
// Client bundles things needed to access the API
type Client struct {
httpClient *http.Client
appID string
appKey string
}
// apiURL is the URL instance used for Oxford API calls
var apiURL *url.URL
// New returns a new Oxford API dictionary source
func New(httpClient http.Client, appID, appKey string) *Client {
return &Client{&httpClient, appID, appKey}
}
// Initialize the package
func init() {
var err error
apiURL, err = url.Parse(baseURLString)
if nil != err {
panic(err)
}
}
// Define takes a word string and returns a dictionary source.Result
func (g *Client) Define(word string) (*Results, error) {
// Prepare our URL
requestURL, err := url.Parse(entriesURLString + "en/" + word)
if nil != err {
return nil, err
}
httpRequest, err := http.NewRequest(http.MethodGet, apiURL.ResolveReference(requestURL).String(), nil)
if nil != err {
return nil, err
}
httpRequest.Header.Set(httpRequestAcceptHeaderName, jsonMIMEType)
httpRequest.Header.Set(httpRequestAppIDHeaderName, g.appID)
httpRequest.Header.Set(httpRequestAppKeyHeaderName, g.appKey)
httpResponse, err := g.httpClient.Do(httpRequest)
if nil != err {
return nil, err
}
defer httpResponse.Body.Close()
if http.StatusNotFound == httpResponse.StatusCode {
return nil, &source.EmptyResultError{Word: word}
}
if http.StatusForbidden == httpResponse.StatusCode {
return nil, &source.AuthenticationError{}
}
body, err := ioutil.ReadAll(httpResponse.Body)
if nil != err {
return nil, err
}
var result Results
if err = json.Unmarshal(body, &result); nil != err {
return nil, err
}
if len(result.Results) < 1 {
return nil, &source.EmptyResultError{Word: word}
}
return &result, nil
}