-
Notifications
You must be signed in to change notification settings - Fork 0
/
dispatch.go
95 lines (79 loc) · 1.87 KB
/
dispatch.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
package ironclad
import (
"golang.org/x/net/context"
"net/http"
"strings"
)
type Template interface {
Template() string
}
type Redirect interface {
NewURL() string
}
type NewSubject interface {
Subject() *Subject
}
type Handler func(s *Subject, c context.Context, r *http.Request) (Template, error)
func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// read environment from the request
c := contextForRequest(r)
s := (*Subject)(nil)
if cookie, _ := r.Cookie("session"); cookie != nil {
s, _ = ParseSubject(c, cookie.Value) // TODO: possibly log this
}
// invoke the handler
t, err := h(s, c, r)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
// write out new session
if t, ok := t.(NewSubject); ok {
s = t.Subject()
}
ss, err := s.Serialize(c)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
http.SetCookie(w, &http.Cookie{
Name: "session",
Value: ss,
Path: "/",
})
// possibly redirect somewhere else
if t, ok := t.(Redirect); ok && t.NewURL() != "" {
http.Redirect(w, r, t.NewURL(), 303)
return
}
// handle empty responses
if t == nil {
http.NotFound(w, r)
return
}
// actually render the template
if err := templateAssets().ExecuteTemplate(w, t.Template(), t); err != nil {
http.Error(w, err.Error(), 500)
return
}
}
func New() http.Handler {
mux := http.NewServeMux()
mux.Handle("/", Handler(SearchListings))
mux.Handle("/edit/", Handler(EditListing))
mux.Handle("/view/", Handler(ViewListing))
mux.Handle("/create", Handler(CreateListing))
mux.Handle("/login", Handler(LoginPage))
mux.Handle("/logout", Handler(LogoutPage))
mux.Handle("/saml-callback", Handler(SAMLRedirect))
mux.Handle("/static/", http.FileServer(staticAssets()))
return mux
}
func idFrom(r *http.Request) ID {
b := strings.Split(r.URL.Path, "/")
if len(b) >= 3 {
return ID(b[2])
} else {
return ID("")
}
}