-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.go
44 lines (36 loc) · 832 Bytes
/
api.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
package main
import (
"encoding/xml"
"errors"
"net/http"
)
// Note that APIKEY is defined elsewhere and not uploaded.
const (
APIURL = "https://www.dictionaryapi.com/api/v1/references/collegiate/xml/"
)
var (
NoDefinitionsError = errors.New("No definitions found")
)
func Definitions(word string) ([]string, error) {
// Download the raw xml data
resp, err := http.Get(APIURL + word + "?key=" + APIKEY)
if err != nil {
return nil, err
}
// API result's format
type Response struct {
Definitions []string `xml:"entry>def>dt"`
}
// Parse out the defintions from the xml
v := &Response{}
dec := xml.NewDecoder(resp.Body)
err = dec.Decode(v)
if err != nil {
return nil, err
}
// Check that there was a result
if len(v.Definitions) == 0 {
return nil, NoDefinitionsError
}
return v.Definitions, nil
}