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
/
Copy pathapi.go
71 lines (62 loc) · 1.39 KB
/
api.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
package main
import (
"fmt"
"net/http"
"net/url"
"time"
log "github.com/Sirupsen/logrus"
"github.com/brycekahle/prerender/render"
)
func handle(w http.ResponseWriter, r *http.Request) {
reqURL := r.URL.Path[1:]
if reqURL == "" {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprint(w, "url is required")
return
}
u, err := url.Parse(reqURL)
if err != nil || !u.IsAbs() {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprint(w, "Invalid URL")
return
}
r.URL.Path = reqURL
res, err := getData(r)
writeResult(res, err, w)
}
func getData(r *http.Request) (*render.Result, error) {
cache := getCache(r.Context())
if cache != nil {
res, err := cache.Check(r)
if err != nil || res != nil {
return res, err
}
}
renderer := getRenderer(r.Context())
res, err := renderer.Render(r.URL.Path)
if err == nil && res.Status == http.StatusOK && cache != nil {
err = cache.Save(res, 24*time.Hour)
}
return res, err
}
func writeResult(res *render.Result, err error, w http.ResponseWriter) {
if err != nil {
if err == render.ErrPageLoadTimeout {
w.WriteHeader(http.StatusGatewayTimeout)
} else {
w.WriteHeader(http.StatusInternalServerError)
log.WithError(err).Errorf("error rendering")
}
return
}
if res.Status != http.StatusOK {
w.WriteHeader(res.Status)
return
}
if res.Etag != "" {
w.Header().Add("Etag", res.Etag)
}
if res.HTML != "" {
fmt.Fprint(w, res.HTML)
}
}