-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
92 lines (78 loc) · 2.47 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
89
90
91
92
package main
import (
"context"
"flag"
"net"
"net/http"
"os"
"time"
_ "net/http/pprof"
"github.com/julienschmidt/httprouter"
)
const (
appName = "cheshire-east-bin-collection-ics"
appVersion = "0.2"
fetchURL = "https://online.cheshireeast.gov.uk/MyCollectionDay/SearchByAjax/GetBartecJobList?uprn="
calendarName = "collections.ics"
)
func main() {
envUPRN := os.Getenv("UPRN")
flagUPRN := flag.String("uprn", "", "Your Unique Property Reference Number (UPRN)")
flagUpdateInterval := flag.Duration("updateInterval", time.Hour*24, "Data younger than this value will be served from the cache")
flagBindAddr := flag.String("http", ":8080", "The address and/or port to bind to the HTTP server")
flagLogQuiet := flag.Bool("q", false, "Disables all logging except for errors")
flagPprofAddr := flag.String("pprof", "localhost:6060", "The address and/or port to bind to the pprof HTTP server")
flag.Parse()
s := server{
Logger: newDefaultLogger(*flagLogQuiet),
router: httprouter.New(),
httpClient: http.DefaultClient,
updateInterval: *flagUpdateInterval,
cache: NewCollections(),
cachedAt: time.Time{},
}
ctx := context.Background()
uprn := *flagUPRN
if uprn == "" {
uprn = envUPRN
}
if uprn == "" {
s.Log(LevelError, ctx, "UPRN was not set. Set with \"UPRN\" env var or -uprn=\"your-uprn\" flag")
os.Exit(1)
}
if *flagUpdateInterval < time.Hour*24 {
s.Log(LevelError, ctx, "Invalid updateInterval set. Must be at least 24h")
os.Exit(1)
} else if *flagUpdateInterval > time.Hour*24*7 {
s.Log(LevelError, ctx, "Invalid updateInterval set. Must be at most 168h (7 days)")
os.Exit(1)
}
if *flagPprofAddr != "" {
l, err := net.Listen("tcp", *flagPprofAddr)
if err != nil {
s.Log(LevelError, ctx, "Error listening on %v: %v", *flagPprofAddr, err)
os.Exit(1)
}
s.Log(LevelDebug, ctx, "Serving pprof at http://%s/debug/pprof/...", l.Addr().String())
go func() {
err = http.Serve(l, nil)
if err != nil {
s.Log(LevelError, ctx, "Error from pprof HTTP server: %v", err)
os.Exit(1)
}
}()
}
s.uprn = uprn
s.routes()
l, err := net.Listen("tcp", *flagBindAddr)
if err != nil {
s.Log(LevelError, ctx, "Error listening on %v: %v", *flagBindAddr, err)
os.Exit(1)
}
s.Log(LevelAll, ctx, "Serving calendar at http://%s/%s", l.Addr().String(), calendarName)
err = http.Serve(l, s.middleware(s.router))
if err != nil {
s.Log(LevelError, ctx, "Error from HTTP server: %v", err)
os.Exit(1)
}
}