commit c90b724307685b02401f6c7b9de92273c345a4aa Author: stephen mcquay Date: Fri Jan 23 15:10:12 2015 -0800 init diff --git a/main.go b/main.go new file mode 100644 index 0000000..2567c63 --- /dev/null +++ b/main.go @@ -0,0 +1,85 @@ +package main + +import ( + "encoding/json" + "fmt" + "go/doc" + "log" + "math" + "net/http" + "os" + "sort" + "strings" +) + +const url = "http://api.urbandictionary.com/v0/define?term=" +const usage = "ud " + +type response struct { + Results []result `json:"list"` +} + +type result struct { + Definition string `json:"definition"` + Example string `json:"example"` + Link string `json:"permalink"` + Author string `json:"author"` + + Up int `json:"thumbs_up"` + Down int `json:"thumbs_down"` +} + +type ByVotes []result + +func (bv ByVotes) Len() int { + return len(bv) +} + +func (bv ByVotes) Swap(i, j int) { + bv[i], bv[j] = bv[j], bv[i] +} +func (bv ByVotes) Less(i, j int) bool { + return math.Abs(float64(bv[i].Up-bv[i].Down)) > math.Abs(float64(bv[j].Up-bv[j].Down)) +} + +func main() { + if len(os.Args) < 2 { + fmt.Fprintf(os.Stderr, "%s\n", usage) + os.Exit(1) + } + + words := os.Args[1:] + u := fmt.Sprintf("%s%s", url, strings.Join(words, "+")) + + resp, err := http.Get(u) + if err != nil { + log.Fatal(err) + } + data := response{} + err = json.NewDecoder(resp.Body).Decode(&data) + resp.Body.Close() + if err != nil { + log.Fatal(err) + } + + sort.Sort(ByVotes(data.Results)) + + for i, res := range data.Results { + fmt.Printf( + "%d:\n", + i, + ) + doc.ToText(os.Stdout, res.Definition, "\t", "", 80) + fmt.Printf( + "\n\n\texample:\n\t%s\n", + strings.Replace(res.Example, "\r\n", "\n\t", -1), + ) + fmt.Printf( + "\n\t%s\n\t^ %d, v %d\n\t%s\n", + res.Link, + res.Up, + res.Down, + res.Author, + ) + } +}