-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
datamuse.go
60 lines (47 loc) · 1.09 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
54
55
56
57
58
59
60
/*
Using datamuse.com API and its /words endpoint.
This service functions without restriction and without an API key for up to 100,000 requests per day.
*/
package common
import (
"encoding/json"
"io/ioutil"
"math/rand"
"net/http"
)
func wordFromAPI(wrd string, synSwitch bool) string {
type wordFromAPI struct {
Word string `json:"word"`
}
var words []wordFromAPI
var response = wrd
var code = "ant="
if synSwitch {
code = "syn="
}
queryURL := "https://api.datamuse.com/words?rel_" + code + wrd
req, err := http.NewRequest("GET", queryURL, nil)
if err != nil {
return response
}
req.Header.Set("User-Agent", "curlPAGST/7.65.1")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return response
}
if resp.StatusCode != 200 {
return response
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return response
}
queryErr := json.Unmarshal([]byte(body), &words)
if queryErr != nil {
return response
}
if len(words) > 0 {
response = words[rand.Intn(len(words))].Word
}
return response
}