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 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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. // ByVotes aids in sorting result based on votes
  32. type ByVotes []result
  33. func (bv ByVotes) Len() int {
  34. return len(bv)
  35. }
  36. func (bv ByVotes) Swap(i, j int) {
  37. bv[i], bv[j] = bv[j], bv[i]
  38. }
  39. func (bv ByVotes) Less(i, j int) bool {
  40. return float64(bv[i].Up-bv[i].Down) > float64(bv[j].Up-bv[j].Down)
  41. }
  42. func main() {
  43. flag.Parse()
  44. if len(flag.Args()) < 1 {
  45. fmt.Fprintf(os.Stderr, "%s\n", usage)
  46. os.Exit(1)
  47. }
  48. u := fmt.Sprintf("%s%s", url, strings.Join(flag.Args(), "+"))
  49. resp, err := http.Get(u)
  50. if err != nil {
  51. log.Fatal(err)
  52. }
  53. data := response{}
  54. err = json.NewDecoder(resp.Body).Decode(&data)
  55. resp.Body.Close()
  56. if err != nil {
  57. log.Fatal(err)
  58. }
  59. sort.Sort(ByVotes(data.Results))
  60. if !all {
  61. if len(data.Results) > 0 {
  62. data.Results = data.Results[:1]
  63. }
  64. }
  65. for i, res := range data.Results {
  66. if i > 0 {
  67. fmt.Printf("\n\n")
  68. }
  69. if all {
  70. fmt.Printf(
  71. "Definition %d:\n",
  72. i+1,
  73. )
  74. }
  75. doc.ToText(os.Stdout, res.Definition, "", "", 80)
  76. res.Example = strings.Replace(res.Example, "\r\n", "\n", -1)
  77. res.Example = strings.Replace(res.Example, "\n", "\n ", -1)
  78. fmt.Printf("\n\n Example:\n %s\n", res.Example)
  79. fmt.Printf(
  80. "\nSource: %s\nUp: %d, Down: %d\nAuthor: %s\n",
  81. res.Link,
  82. res.Up,
  83. res.Down,
  84. res.Author,
  85. )
  86. }
  87. }