This repository has been archived by the owner on Jan 23, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
85 lines (76 loc) · 1.99 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
package main
import (
"fmt"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"context"
log "github.com/Sirupsen/logrus"
"github.com/brycekahle/prerender/cache"
"github.com/brycekahle/prerender/render"
"github.com/felixge/httpsnoop"
"github.com/go-redis/redis"
)
func main() {
var renderer render.Renderer
var err error
renderer, err = render.NewRenderer()
if err != nil {
log.Fatal(err)
}
defer renderer.Close()
if os.Getenv("RENDER_TIMEOUT") != "" {
if t, perr := time.ParseDuration(os.Getenv("RENDER_TIMEOUT")); perr == nil {
renderer.SetPageLoadTimeout(t)
}
}
redisAddr := os.Getenv("REDIS_URL")
if redisAddr == "" {
redisAddr = "redis://localhost:6379/0"
}
opts, err := redis.ParseURL(redisAddr)
if err != nil {
log.Fatal("error parsing redis url", err)
}
client := redis.NewClient(opts)
defer client.Close()
// a custom handler is necessary because ServeMux redirects // to /
// in all urls, regardless of escaping
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := setRenderer(r.Context(), renderer)
ctx = setCache(ctx, cache.NewCache(client))
handle(w, r.WithContext(ctx))
})
wrappedHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
m := httpsnoop.CaptureMetrics(handler, w, r)
log.WithFields(log.Fields{
"method": r.Method,
"path": r.URL.Path,
"status": m.Code,
"duration": m.Duration.Nanoseconds(),
"size": m.Written,
}).Infof("Completed request")
})
port := os.Getenv("PORT")
if port == "" {
port = "8000"
}
l := fmt.Sprintf(":%s", port)
log.Printf("listening on %s", l)
server := http.Server{Addr: l, Handler: wrappedHandler}
go func() {
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
<-c
log.Info("signal caught, shutting down")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
server.Shutdown(ctx)
}()
err = server.ListenAndServe()
if err != http.ErrServerClosed {
log.Error(err)
}
}