-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.go
More file actions
63 lines (54 loc) · 1.42 KB
/
middleware.go
File metadata and controls
63 lines (54 loc) · 1.42 KB
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
package main
import (
"encoding/json"
"log"
"net/http"
"github.com/devilcove/cookie"
)
// Logger is a logging middleware that logs useragent, RemoteAddr, Method, Host, Path and response.Status to stdlib log.
func Logger(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
rec := statusRecorder{w, http.StatusOK}
next.ServeHTTP(&rec, r)
remote := r.RemoteAddr
if r.Header.Get("X-Forwarded-For") != "" {
remote = r.Header.Get("X-Forwarded-For")
}
log.Println(remote, r.Method, r.Host, r.URL.Path, rec.status, r.UserAgent())
})
}
type statusRecorder struct {
http.ResponseWriter
status int
}
// WriteHeader overrides std WriteHeader func to save response code.
func (rec *statusRecorder) WriteHeader(code int) {
rec.status = code
rec.ResponseWriter.WriteHeader(code)
}
func auth(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if _, err := cookie.Get(r, cookieName); err != nil {
w.WriteHeader(http.StatusUnauthorized)
displayLogin(w, r)
return
}
next.ServeHTTP(w, r)
})
}
func sessionUser(r *http.Request) (User, error) {
user := User{}
data, err := cookie.Get(r, cookieName)
if err != nil {
return user, err
}
err = json.Unmarshal(data, &user)
return user, err
}
func isAdmin(r *http.Request) bool {
user, err := sessionUser(r)
if err != nil {
return false
}
return user.Admin
}