-
Notifications
You must be signed in to change notification settings - Fork 54
/
main.go
88 lines (77 loc) · 1.82 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
88
package main
import (
"flag"
"fmt"
"html/template"
"log"
"net/http"
"net/url"
"strings"
"time"
"github.com/gophercises/quiet_hn/hn"
)
func main() {
// parse flags
var port, numStories int
flag.IntVar(&port, "port", 3000, "the port to start the web server on")
flag.IntVar(&numStories, "num_stories", 30, "the number of top stories to display")
flag.Parse()
tpl := template.Must(template.ParseFiles("./index.gohtml"))
http.HandleFunc("/", handler(numStories, tpl))
// Start the server
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", port), nil))
}
func handler(numStories int, tpl *template.Template) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
var client hn.Client
ids, err := client.TopItems()
if err != nil {
http.Error(w, "Failed to load top stories", http.StatusInternalServerError)
return
}
var stories []item
for _, id := range ids {
hnItem, err := client.GetItem(id)
if err != nil {
continue
}
item := parseHNItem(hnItem)
if isStoryLink(item) {
stories = append(stories, item)
if len(stories) >= numStories {
break
}
}
}
data := templateData{
Stories: stories,
Time: time.Now().Sub(start),
}
err = tpl.Execute(w, data)
if err != nil {
http.Error(w, "Failed to process the template", http.StatusInternalServerError)
return
}
})
}
func isStoryLink(item item) bool {
return item.Type == "story" && item.URL != ""
}
func parseHNItem(hnItem hn.Item) item {
ret := item{Item: hnItem}
url, err := url.Parse(ret.URL)
if err == nil {
ret.Host = strings.TrimPrefix(url.Hostname(), "www.")
}
return ret
}
// item is the same as the hn.Item, but adds the Host field
type item struct {
hn.Item
Host string
}
type templateData struct {
Stories []item
Time time.Duration
}