This repository has been archived by the owner on May 21, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.go
81 lines (60 loc) · 1.9 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
package api
import (
"context"
"fmt"
"net/http"
"time"
"github.com/go-chi/chi"
"github.com/google/uuid"
"github.com/jinzhu/gorm"
logrus "github.com/sirupsen/logrus"
session "github.com/chaostreff-flensburg/moc/context"
"github.com/chaostreff-flensburg/moc/models"
"github.com/chaostreff-flensburg/moc/router"
)
// withMessageID load message entity by request param
func (api *API) withMessageID(w http.ResponseWriter, r *http.Request) (context.Context, error) {
messageID := chi.URLParam(r, "messageID")
if _, err := uuid.Parse(messageID); err != nil {
return nil, router.BadRequestError("bad messageID").WithInternalError(err)
}
var message models.Message
if res := api.db.First(&message, models.Message{ID: messageID}); res.Error != nil {
if gorm.IsRecordNotFoundError(res.Error) {
return nil, router.NotFoundError("message not found")
}
return nil, router.HandleSQLError(res.Error)
}
ctx := r.Context()
ctx = session.WithMessage(ctx, &message)
return ctx, nil
}
// withLogger add request details to log output
func (api *API) withLogger(w http.ResponseWriter, r *http.Request) (context.Context, error) {
ctx := r.Context()
logFields := logrus.Fields{}
logFields["ts"] = time.Now().UTC().Format(time.RFC1123)
if reqID := session.GetRequestID(ctx); reqID != nil {
logFields["req_id"] = *reqID
}
scheme := "http"
if r.TLS != nil {
scheme = "https"
}
logFields["uri"] = fmt.Sprintf("%s://%s%s", scheme, r.Host, r.RequestURI)
requestLogger := api.log.WithFields(logFields)
ctx = context.WithValue(ctx, "log", requestLogger)
return ctx, nil
}
// withRequestID add request id to log
func withRequestID(w http.ResponseWriter, r *http.Request) (context.Context, error) {
id := uuid.New().String()
oldID := r.Header.Get("X-Request-ID")
if oldID != "" {
id = oldID
}
ctx := r.Context()
ctx = session.WithRequestID(ctx, &id)
w.Header().Set("X-Request-ID", id)
return ctx, nil
}