summaryrefslogtreecommitdiff
path: root/urban.go
diff options
context:
space:
mode:
Diffstat (limited to 'urban.go')
-rw-r--r--urban.go72
1 files changed, 72 insertions, 0 deletions
diff --git a/urban.go b/urban.go
new file mode 100644
index 0000000..aa13606
--- /dev/null
+++ b/urban.go
@@ -0,0 +1,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 noMatches = 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{}, noMatches
+}