From 5e8a999bce349701001c0e987792e78a7296e87f Mon Sep 17 00:00:00 2001 From: Dimitri Sokolyuk Date: Tue, 21 Jul 2015 14:53:50 +0200 Subject: Initial import --- urban.go | 72 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 urban.go 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 +} -- cgit v1.2.3