-
Notifications
You must be signed in to change notification settings - Fork 1
/
datamuse.go
53 lines (43 loc) · 1.07 KB
/
datamuse.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
package datamuse
import (
"encoding/json"
"net/http"
"net/url"
"time"
)
// Datamuse is the wrapper of all package's requests.
type Datamuse struct {
apiURL *url.URL
}
// Results represent a single Datamuse results.
type Result struct {
Word string `json:"word"`
Score int `json:"score"`
SyllablesCount uint `json:"numSyllables,omitempty"`
Tags []string `json:"tags,omitempty"`
}
// Results represent a list of Datamuse results.
type Results []Result
// New create a new Datamuse instance.
func New() *Datamuse {
u, _ := url.Parse("https://api.datamuse.com")
return &Datamuse{
apiURL: u,
}
}
// Get creates a GET request to the apiURL and parses results.
func (dm *Datamuse) Get() (Results, error) {
c := &http.Client{Timeout: 30 * time.Second}
resp, err := c.Get(dm.apiURL.String())
if err != nil {
return nil, err
}
defer resp.Body.Close()
var res Results
err = json.NewDecoder(resp.Body).Decode(&res)
return res, err
}
// URL returns the apiURL as string.
func (dm *Datamuse) URL() string {
return dm.apiURL.String()
}