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: search for term on urban dictionary\n\nusage: ud \n" 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, ) } }