-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
87 lines (73 loc) · 1.54 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 (
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"time"
"github.com/pkg/errors"
)
var location *time.Location
func enableCors(w *http.ResponseWriter) {
(*w).Header().Set("Access-Control-Allow-Origin", "*")
}
func setupRouter(fetcher APIFetcher) {
http.HandleFunc("/v1/live", func(w http.ResponseWriter, r *http.Request) {
enableCors(&w)
live := fetcher.Live()
if err := json.NewEncoder(w).Encode(live); err != nil {
w.WriteHeader(500)
w.Write([]byte(err.Error()))
return
}
})
}
func main() {
timezone := os.Getenv("API_TIMEZONE")
if timezone == "" {
log.Fatal("missing API_TIMEZONE env var")
}
l, err := time.LoadLocation(timezone)
if err != nil {
log.Fatal(errors.Wrap(err, "could not load timezone"))
}
location = l
apiHost := os.Getenv("API_HOST")
if apiHost == "" {
log.Fatal("missing API_HOST env var")
}
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
host := os.Getenv("HOST")
fetcher := &apiFetcher{
host: apiHost,
client: &http.Client{
Timeout: 2 * time.Second,
},
}
setupRouter(fetcher)
// Handle Ctrl+C
var quit chan os.Signal
quit = make(chan os.Signal, 1)
signal.Notify(quit, os.Interrupt)
tick := time.NewTicker(time.Second).C
go func() {
for {
select {
case <-quit:
log.Println("exiting...")
os.Exit(0)
case <-tick:
if err := fetcher.PollAPI(); err != nil {
log.Println(err)
}
}
}
}()
log.Printf("listening on %s:%s\n", host, port)
log.Fatal(http.ListenAndServe(fmt.Sprintf("%s:%s", host, port), nil))
}