forked from sourcegraph/thesrc
/
handler.go
97 lines (84 loc) · 2.4 KB
/
handler.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
93
94
95
96
97
package app
import (
"bytes"
"errors"
"fmt"
"log"
"net/http"
"path/filepath"
"runtime/debug"
"github.com/gorilla/mux"
"github.com/gorilla/schema"
"sourcegraph.com/sourcegraph/thesrc"
"sourcegraph.com/sourcegraph/thesrc/router"
)
var (
// ReloadTemplates is whether to reload templates on each request.
ReloadTemplates bool
// StaticDir is the directory containing static assets.
StaticDir = filepath.Join(defaultBase("sourcegraph.com/sourcegraph/thesrc/app"), "static")
)
var (
APIClient = thesrc.NewClient(nil)
schemaDecoder = schema.NewDecoder()
appRouter = router.App()
)
func Handler() *mux.Router {
m := appRouter
m.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir(StaticDir))))
// TODO(sqs): add handlers for /favicon.ico and /robots.txt
m.Get(router.Post).Handler(handler(servePost))
m.Get(router.Posts).Handler(handler(servePosts))
m.Get(router.SubmitPostForm).Handler(handler(serveSubmitPostForm))
m.Get(router.SubmitPost).Handler(handler(serveSubmitPost))
return m
}
type handler func(resp http.ResponseWriter, req *http.Request) error
func (h handler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
if ReloadTemplates {
LoadTemplates()
}
runHandler(resp, req, h)
}
func runHandler(w http.ResponseWriter, r *http.Request, fn func(http.ResponseWriter, *http.Request) error) {
var err error
defer func() {
if rv := recover(); rv != nil {
err = errors.New("handler panic")
logError(r, err, rv)
handleError(w, r, http.StatusInternalServerError, err)
}
}()
err = fn(w, r)
if err != nil {
logError(r, err, nil)
handleError(w, r, http.StatusInternalServerError, err)
}
}
func handleError(w http.ResponseWriter, r *http.Request, status int, err error) {
w.Header().Set("cache-control", "no-cache")
err2 := renderTemplate(w, r, "error.html", status, &struct {
StatusCode int
Status string
Err error
templateCommon
}{
StatusCode: status,
Status: http.StatusText(status),
Err: err,
})
if err2 != nil {
logError(r, fmt.Errorf("during execution of error template: %s", err2), nil)
}
}
func logError(req *http.Request, err error, rv interface{}) {
if err != nil {
var buf bytes.Buffer
fmt.Fprintf(&buf, "Error serving %s (route %s): %s\n", req.URL, mux.CurrentRoute(req).GetName(), err)
if rv != nil {
fmt.Fprintln(&buf, rv)
buf.Write(debug.Stack())
}
log.Print(buf.String())
}
}