-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.go
94 lines (82 loc) · 2.16 KB
/
middleware.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
package middleware
import (
"net/http"
"log"
"time"
"github.com/rs/xid"
"github.com/vuonghp92/grpc-mcro-demo/front/session"
"github.com/vuonghp92/grpc-mcro-demo/front/support"
pbUser "github.com/vuonghp92/grpc-mcro-demo/proto/user"
)
const (
xRequestIDKey = "X-Request-Id"
)
func Tracing(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
traceID := r.Header.Get(xRequestIDKey)
if traceID == "" {
traceID = newTraceID()
}
ctx := support.AddTraceIDToContext(
r.Context(),
traceID)
r = r.WithContext(ctx)
next.ServeHTTP(w, r)
})
}
func newTraceID() string {
return xid.New().String()
}
const loggingFmt = "TraceID: %s\tMethod: %s\tPath: %s\tElapsedTime: %s\tStatusCode: %d\n"
type loggingResponseWriter struct {
http.ResponseWriter
statusCode int
}
func (lrw *loggingResponseWriter) WriteHeader(code int) {
lrw.statusCode = code
lrw.ResponseWriter.WriteHeader(code)
}
func Logging(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
lrw := &loggingResponseWriter{ResponseWriter: w, statusCode: 200}
defer func() {
log.Printf(loggingFmt,
support.GetTraceIDFromContext(r.Context()),
r.Method,
r.URL.String(),
time.Since(start),
lrw.statusCode)
}()
next.ServeHTTP(w, r)
})
}
func NewAuthentication(
userClient pbUser.UserServiceClient,
sessionStore session.Store) func(next http.HandlerFunc) http.HandlerFunc {
return func(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
sessionID := session.GetSessionIDFromRequest(r)
v, ok := sessionStore.Get(sessionID)
if !ok {
http.Redirect(w, r, "/login", http.StatusFound)
return
}
userID, ok := v.(uint64)
if !ok {
http.Redirect(w, r, "/login", http.StatusFound)
return
}
ctx := r.Context()
resp, err := userClient.FindUser(ctx, &pbUser.FindUserRequest{
UserId: userID,
})
if err != nil {
http.Redirect(w, r, "/login", http.StatusFound)
return
}
ctx = support.AddUserToContext(ctx, resp.User)
next.ServeHTTP(w, r.WithContext(ctx))
}
}
}