-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhn.go
110 lines (91 loc) · 1.74 KB
/
hn.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package main
import (
"encoding/xml"
"fmt"
"html"
"io/ioutil"
"log"
"net/http"
"os"
"strconv"
"strings"
"github.com/fatih/color"
"github.com/skratchdot/open-golang/open"
)
type Item struct {
Title string `xml:"title"`
Link string `xml:"link"`
}
type Channel struct {
Items []Item `xml:"item"`
}
type Result struct {
Channel Channel `xml:"channel"`
}
func fetchRSS(url string) []Item {
resp, err := http.Get(url)
if err != nil {
log.Fatalf("error: %v", err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatalf("error: %v", err)
}
var v Result
err = xml.Unmarshal(body, &v)
if err != nil {
log.Fatalf("error: %v", err)
}
return v.Channel.Items
}
func displayRSS(items []Item) {
for i, item := range items {
index := i + 1
color.Set(color.FgRed)
fmt.Printf("%2d.", index)
color.Unset()
fmt.Printf(" %s\n", html.UnescapeString(item.Title))
}
}
func bound(i, lower, upper int) int {
if i < lower {
return lower
} else if i > upper {
return upper
} else {
return i
}
}
func main() {
var items []Item
var input string
refresh := true
var prompt = color.New(color.FgBlue).PrintfFunc()
for {
if refresh {
items = fetchRSS("https://news.ycombinator.com/rss")
displayRSS(items)
refresh = false
}
prompt("Type post number to open, (r) to refresh, (q) to quit: ")
fmt.Scanln(&input)
if strings.ToLower(input) == "r" {
refresh = true
continue
}
if strings.ToLower(input) == "q" {
fmt.Println("Good bye!")
os.Exit(0)
}
i, err := strconv.Atoi(input)
if err != nil {
color.Yellow("Try again")
continue
}
i = bound(i, 1, len(items))
open.Run(items[i-1].Link) // open in default browser
fmt.Println()
displayRSS(items)
}
}