summaryrefslogtreecommitdiff
path: root/urban.go
blob: 6a1fb478368a3e8dfdb08faff1129f32002454c9 (plain)
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
package urban

import (
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"sort"
)

const baseURL = `http://api.urbandictionary.com/v0/define?term=%s`

type Answer struct {
	List       []Entry  `json:"list"`
	ResultType string   `json:"result_type"`
	Sounds     []string `json:"sounds"`
	Tags       []string `json:"tags"`
}

type Entry struct {
	Author      string `json:"author"`
	CurrentVote string `json:"current_vote"`
	DefID       int    `json:"defid"`
	Definition  string `json:"definition"`
	Example     string `json:"example"`
	Permalink   string `json:"permalink"`
	ThumbsDown  int    `json:"thumbs_down"`
	ThumbsUp    int    `json:"thumbs_up"`
	Word        string `json:"word"`
}

var ErrNoMatches = errors.New("no matches")

type byRatio []Entry

func (l byRatio) Len() int      { return len(l) }
func (l byRatio) Swap(i, j int) { l[i], l[j] = l[j], l[i] }
func (l byRatio) Less(i, j int) bool {
	a := float64(l[i].ThumbsUp) / float64(l[i].ThumbsDown)
	b := float64(l[j].ThumbsUp) / float64(l[j].ThumbsDown)
	return a < b
}

func Query(q string) (Answer, error) {
	s := fmt.Sprintf(baseURL, url.QueryEscape(q))
	resp, err := http.Get(s)
	if err != nil {
		return Answer{}, err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return Answer{}, err
	}
	a := Answer{}
	err = json.Unmarshal(body, &a)
	return a, err
}

func QueryTop(q string) (Entry, error) {
	a, err := Query(q)
	if err != nil {
		return Entry{}, err
	}
	if len(a.List) > 0 {
		sort.Sort(sort.Reverse(byRatio(a.List)))
		return a.List[0], nil
	}
	return Entry{}, ErrNoMatches
}