-
Notifications
You must be signed in to change notification settings - Fork 0
/
ghost.go
75 lines (66 loc) · 1.55 KB
/
ghost.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
package handlers
import (
"net/http"
)
// Interface giving easy access to the most common augmented features.
type GhostWriter interface {
http.ResponseWriter
UserName() string
User() interface{}
Context() map[interface{}]interface{}
Session() *Session
}
// Internal implementation of the GhostWriter interface.
type ghostWriter struct {
http.ResponseWriter
userName string
user interface{}
ctx map[interface{}]interface{}
ssn *Session
}
func (this *ghostWriter) UserName() string {
return this.userName
}
func (this *ghostWriter) User() interface{} {
return this.user
}
func (this *ghostWriter) Context() map[interface{}]interface{} {
return this.ctx
}
func (this *ghostWriter) Session() *Session {
return this.ssn
}
// Convenience handler that wraps a custom function with direct access to the
// authenticated user, context and session on the writer.
func GhostHandlerFunc(h func(w GhostWriter, r *http.Request)) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if gw, ok := getGhostWriter(w); ok {
// Self-awareness
h(gw, r)
return
}
uid, _ := GetUserName(w)
usr, _ := GetUser(w)
ctx, _ := GetContext(w)
ssn, _ := GetSession(w)
gw := &ghostWriter{
w,
uid,
usr,
ctx,
ssn,
}
h(gw, r)
}
}
// Check the writer chain to find a ghostWriter.
func getGhostWriter(w http.ResponseWriter) (*ghostWriter, bool) {
gw, ok := GetResponseWriter(w, func(tst http.ResponseWriter) bool {
_, ok := tst.(*ghostWriter)
return ok
})
if ok {
return gw.(*ghostWriter), true
}
return nil, false
}