-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathweb_session_middleware.go
69 lines (58 loc) · 1.64 KB
/
web_session_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
package edatpgx
import (
"context"
"fmt"
"net/http"
"github.com/jackc/pgx/v4/pgxpool"
"github.com/stackus/edat/log"
)
func WebSessionMiddleware(conn *pgxpool.Pool, logger log.Logger) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
tx, err := conn.Begin(r.Context())
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
_, _ = fmt.Fprintf(w, "failed to start transaction: %s", err.Error())
logger.Error("error while starting the request transaction", log.Error(err))
return
}
ww := newStatusWriter(w)
ctx := context.WithValue(r.Context(), pgxTxKey, tx)
defer func() {
p := recover()
switch {
case p != nil:
txErr := tx.Rollback(r.Context())
if txErr != nil {
logger.Error("error while rolling back the web request transaction during panic", log.Error(txErr))
}
panic(p)
case ww.status > 399:
txErr := tx.Rollback(r.Context())
if txErr != nil {
logger.Error("error while rolling back the web request transaction", log.Error(txErr))
}
default:
txErr := tx.Commit(r.Context())
if txErr != nil {
logger.Error("error while committing the web request transaction", log.Error(txErr))
}
}
}()
next.ServeHTTP(ww, r.WithContext(ctx))
})
}
}
type statusWriter struct {
http.ResponseWriter
status int
}
func newStatusWriter(w http.ResponseWriter) *statusWriter {
return &statusWriter{
ResponseWriter: w,
}
}
func (s *statusWriter) WriteHeader(status int) {
s.status = status
s.ResponseWriter.WriteHeader(status)
}