confirms your hunch that the phrase of which you're thinking is already in urban dictionary
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

main.go 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. package main
  2. import (
  3. "encoding/json"
  4. "flag"
  5. "fmt"
  6. "go/doc"
  7. "log"
  8. "net/http"
  9. "os"
  10. "sort"
  11. "strings"
  12. )
  13. const url = "http://api.urbandictionary.com/v0/define?term="
  14. const usage = "ud: confirm that the term you're thinking of has already been added to urban dictionary\n\nusage: ud <term>\n"
  15. var all bool
  16. func init() {
  17. flag.BoolVar(&all, "all", false, "more than one")
  18. flag.BoolVar(&all, "a", false, "more than one")
  19. }
  20. type response struct {
  21. Results []result `json:"list"`
  22. }
  23. type result struct {
  24. Definition string `json:"definition"`
  25. Example string `json:"example"`
  26. Link string `json:"permalink"`
  27. Author string `json:"author"`
  28. Up int `json:"thumbs_up"`
  29. Down int `json:"thumbs_down"`
  30. }
  31. type ByVotes []result
  32. func (bv ByVotes) Len() int {
  33. return len(bv)
  34. }
  35. func (bv ByVotes) Swap(i, j int) {
  36. bv[i], bv[j] = bv[j], bv[i]
  37. }
  38. func (bv ByVotes) Less(i, j int) bool {
  39. return float64(bv[i].Up-bv[i].Down) > float64(bv[j].Up-bv[j].Down)
  40. }
  41. func main() {
  42. flag.Parse()
  43. if len(flag.Args()) < 1 {
  44. fmt.Fprintf(os.Stderr, "%s\n", usage)
  45. os.Exit(1)
  46. }
  47. u := fmt.Sprintf("%s%s", url, strings.Join(flag.Args(), "+"))
  48. resp, err := http.Get(u)
  49. if err != nil {
  50. log.Fatal(err)
  51. }
  52. data := response{}
  53. err = json.NewDecoder(resp.Body).Decode(&data)
  54. resp.Body.Close()
  55. if err != nil {
  56. log.Fatal(err)
  57. }
  58. sort.Sort(ByVotes(data.Results))
  59. if !all {
  60. if len(data.Results) > 0 {
  61. data.Results = data.Results[:1]
  62. }
  63. }
  64. for i, res := range data.Results {
  65. if i > 0 {
  66. fmt.Printf("\n\n")
  67. }
  68. if all {
  69. fmt.Printf(
  70. "Definition %d:\n",
  71. i+1,
  72. )
  73. }
  74. doc.ToText(os.Stdout, res.Definition, "", "", 80)
  75. res.Example = strings.Replace(res.Example, "\r\n", "\n", -1)
  76. res.Example = strings.Replace(res.Example, "\n", "\n ", -1)
  77. fmt.Printf("\n\n Example:\n %s\n", res.Example)
  78. fmt.Printf(
  79. "\nSource: %s\nUp: %d, Down: %d\nAuthor: %s\n",
  80. res.Link,
  81. res.Up,
  82. res.Down,
  83. res.Author,
  84. )
  85. }
  86. }