This commit is contained in:
Stephen McQuay 2016-06-02 11:08:51 -07:00
parent ff42c74ad3
commit e34e623cf2
No known key found for this signature in database
GPG Key ID: 1ABF428F71BAFC3D

101
main.go
View File

@ -1,104 +1,7 @@
package main
import (
"encoding/json"
"flag"
"fmt"
"go/doc"
"log"
"net/http"
"os"
"sort"
"strings"
)
const url = "http://api.urbandictionary.com/v0/define?term="
const usage = "ud: confirm that the term you're thinking of has already been added to urban dictionary\n\nusage: ud <term>\n"
var all bool
func init() {
flag.BoolVar(&all, "all", false, "more than one")
flag.BoolVar(&all, "a", false, "more than one")
}
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"`
}
// ByVotes aids in sorting result based on votes
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 float64(bv[i].Up-bv[i].Down) > float64(bv[j].Up-bv[j].Down)
}
import "fmt"
func main() {
flag.Parse()
if len(flag.Args()) < 1 {
fmt.Fprintf(os.Stderr, "%s\n", usage)
os.Exit(1)
}
u := fmt.Sprintf("%s%s", url, strings.Join(flag.Args(), "+"))
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))
if !all {
if len(data.Results) > 0 {
data.Results = data.Results[:1]
}
}
for i, res := range data.Results {
if i > 0 {
fmt.Printf("\n\n")
}
if all {
fmt.Printf(
"Definition %d:\n",
i+1,
)
}
doc.ToText(os.Stdout, res.Definition, "", "", 80)
res.Example = strings.Replace(res.Example, "\r\n", "\n", -1)
res.Example = strings.Replace(res.Example, "\n", "\n ", -1)
fmt.Printf("\n\n Example:\n %s\n", res.Example)
fmt.Printf(
"\nSource: %s\nUp: %d, Down: %d\nAuthor: %s\n",
res.Link,
res.Up,
res.Down,
res.Author,
)
}
fmt.Println("foo")
}