-
Notifications
You must be signed in to change notification settings - Fork 153
/
wrap_interface.go
190 lines (163 loc) · 4.91 KB
/
wrap_interface.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
package main
import (
"fmt"
"net"
"net/http"
"os"
"strings"
"time"
"golang.org/x/net/context"
log "github.com/Sirupsen/logrus"
auth "github.com/bradrydzewski/go.auth"
uuid "github.com/satori/go.uuid"
)
type ContextHandler interface {
ServeHTTPContext(context.Context, http.ResponseWriter, *http.Request) error
}
// ContextHandlerFunc wraps func(context.Context, ResponseWriter, *Request)
type ContextHandlerFunc func(context.Context, http.ResponseWriter, *http.Request) error
func (f ContextHandlerFunc) ServeHTTPContext(ctx context.Context, w http.ResponseWriter, req *http.Request) error {
return f(ctx, w, req)
}
// ContextAdapter satisfies:
// 1. interface 'ContextHandler'
// 2. interface 'http.Handler'
type ContextAdapter struct {
ctx context.Context
handler ContextHandler // to wrap func(context.Context, ResponseWriter, *Request) error
}
func (ca *ContextAdapter) ServeHTTP(w http.ResponseWriter, req *http.Request) {
if err := ca.handler.ServeHTTPContext(ca.ctx, w, req); err != nil {
// (X)
// w.WriteHeader(http.StatusBadRequest)
// http: multiple response.WriteHeader calls
// recovered from panic: runtime error: invalid memory address
// or nil pointer dereference
// ip, ierr := getIP(req)
// if err != nil {
// log.Warnf("getIP error: %v", ierr)
// }
log.WithFields(log.Fields{
"event_type": "error",
"referrer": req.Referer(),
"ua": req.UserAgent(),
"method": req.Method,
"path": req.URL.Path,
"ip": req.RemoteAddr,
"real_ip": getRealIP(req),
"error": err,
}).Errorln("ServeHTTP error")
// json.NewEncoder(w).Encode(map[string]string{
// "status": "error",
// "message": err.Error(),
// })
}
}
func WithAuthentication(h ContextHandler) ContextHandler {
return ContextHandlerFunc(func(ctx context.Context, w http.ResponseWriter, req *http.Request) error {
user, err := auth.GetUserCookie(req)
// if no active user session then authorize user
if err != nil || user.Id() == "" {
http.Redirect(w, req, auth.Config.LoginRedirect, http.StatusSeeOther)
log.Warnf("unidentified user: %+v", user)
return nil
}
if _, ok := accessibleEmail[user.Email()]; !ok {
auth.DeleteUserCookie(w, req)
http.Redirect(w, req, "http://google.com", http.StatusSeeOther)
log.Warnf("unidentified user: %+v", user)
return nil
}
ctx = context.WithValue(ctx, userKey, &user)
userID := fmt.Sprintf("%+v", user)
globalStorage.Lock()
// (X) this will deadlock
// defer globalStorage.Unlock()
if globalStorage.userIDToData[userID] == nil {
globalStorage.userIDToData[userID] = &data{}
}
globalStorage.Unlock()
return h.ServeHTTPContext(ctx, w, req)
})
}
func WithDatabase(h ContextHandler) ContextHandler {
return ContextHandlerFunc(func(ctx context.Context, w http.ResponseWriter, req *http.Request) error {
ctx = context.WithValue(ctx, odbKey, odb)
ctx = context.WithValue(ctx, xdbKey, xdb)
ctx = context.WithValue(ctx, rdbKey, rdb)
ctx = context.WithValue(ctx, cdbKey, cdb)
return h.ServeHTTPContext(ctx, w, req)
})
}
func WithLogrus(h http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
defer func() {
if err := recover(); err != nil {
log.WithFields(log.Fields{
"event_type": "panic_recover",
"referrer": req.Referer(),
"ua": req.UserAgent(),
"method": req.Method,
"path": req.URL.Path,
"ip": req.RemoteAddr,
"real_ip": getRealIP(req),
"error": err,
}).Errorln("WithLogrus error")
}
}()
start := nowPacific()
h.ServeHTTP(w, req)
took := time.Since(start)
log.WithFields(log.Fields{
"event_type": "web_server",
"referrer": req.Referer(),
"ua": req.UserAgent(),
"method": req.Method,
"path": req.URL.Path,
"ip": req.RemoteAddr,
"real_ip": getRealIP(req),
"uuid": uuid.NewV4(),
}).Debugf("took %s", took)
}
}
func openToAppend(fpath string) (*os.File, error) {
f, err := os.OpenFile(fpath, os.O_RDWR|os.O_APPEND, 0777)
if err != nil {
f, err = os.Create(fpath)
if err != nil {
return f, err
}
}
return f, nil
}
func getIP(req *http.Request) (net.IP, error) {
ip, _, err := net.SplitHostPort(req.RemoteAddr)
if err != nil {
return nil, fmt.Errorf("userip: %q is not IP:port", req.RemoteAddr)
}
userIP := net.ParseIP(ip)
if userIP == nil {
return nil, fmt.Errorf("userip: %q is not IP:port", req.RemoteAddr)
}
return userIP, nil
}
func getRealIP(req *http.Request) string {
ts := []string{"X-Forwarded-For", "x-forwarded-for", "X-FORWARDED-FOR"}
for _, k := range ts {
if v := req.Header.Get(k); v != "" {
return v
}
}
return ""
}
func cleanUp(str string) string {
s := strings.Fields(strings.TrimSpace(str))
return strings.Join(s, " ")
}
func nowPacific() time.Time {
tzone, err := time.LoadLocation("America/Los_Angeles")
if err != nil {
return time.Now()
}
return time.Now().In(tzone)
}