-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
56 lines (48 loc) · 1.15 KB
/
Copy pathmain.go
File metadata and controls
56 lines (48 loc) · 1.15 KB
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
package main
import (
"flag"
"fmt"
"html/template"
"log"
"net/http"
"time"
"./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"))
var client hn.Client
client.Singleton()
http.HandleFunc("/", handler(&client, numStories, tpl))
// Start the server
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", port), nil))
}
func handler(client *hn.Client, numStories int, tpl *template.Template) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
ids, err := client.TopItems()
if err != nil {
log.Fatal(err)
return
}
fmt.Println("Retrieving stories")
stories := client.RetrieveStories(numStories, ids)
data := templateData{
Stories: stories,
Time: time.Now().Sub(start),
}
err = tpl.Execute(w, data)
if err != nil {
log.Fatal(err)
return
}
})
}
type templateData struct {
Stories []*hn.ItemWithUrl
Time time.Duration
}