-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
87 lines (73 loc) · 2.03 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package main
import (
"flag"
"fmt"
"log"
"net/http"
"os"
"os/exec"
"runtime"
"strings"
"github.com/PuerkitoBio/goquery"
)
const (
WOTD_URL = "https://www.dictionary.com/e/word-of-the-day"
MAGENTA = "\033[30;45m"
UNDERLINE = "\033[4m"
NOCOLOR = "\033[0m"
)
func main() {
openInBrowser := flag.Bool("o", false, "Opens word of the day page in browser")
flag.Parse()
if *openInBrowser {
openWotdPageInBrowser(WOTD_URL)
}
res, err := http.Get(WOTD_URL)
if err != nil {
log.Fatal(err)
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
log.Fatalf("status code error %d %s", res.StatusCode, res.Status)
}
doc, err := goquery.NewDocumentFromReader(res.Body)
if err != nil {
log.Fatal("error parsing html page", err)
}
word := doc.Find(".otd-item-headword__word h1.js-fit-text")
definitionAndType := doc.Find(".otd-item-headword__pos-blocks .otd-item-headword__pos p")
wordExamples := doc.Find(".wotd-item-origin__content ul:nth-of-type(2)").Eq(0)
wordType := definitionAndType.Eq(0)
definition := definitionAndType.Eq(1)
formattedExamples := strings.TrimSuffix(
strings.ReplaceAll(wordExamples.Text(), "\n", " \n - "), "\n - ",
)
fmt.Printf("%v: %v\n", colorOutput("Word"), word.First().Text())
fmt.Printf("%v: %v\n", underlineOutput("Word Type"), strings.Trim(wordType.Text(), " \n"))
fmt.Printf("%v: %v\n", underlineOutput("Definition"), definition.Text())
fmt.Printf("%v: %v\n", underlineOutput("Examples"), formattedExamples)
}
func openWotdPageInBrowser(url string) {
switch runtime.GOOS {
case "linux":
open("xdg-open", url)
case "darwin":
open("open", url)
case "windows":
open("start", url)
}
os.Exit(0)
}
func open(program, url string) {
cmd := exec.Command(program, url)
err := cmd.Run()
if err != nil {
log.Fatal("unable to open word of the day page in browser")
}
}
func colorOutput(message string) string {
return fmt.Sprintf("%v %v %v", MAGENTA, message, NOCOLOR)
}
func underlineOutput(message string) string {
return fmt.Sprintf("%v%v%v", UNDERLINE, message, NOCOLOR)
}