-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtx.go
52 lines (43 loc) · 1.08 KB
/
tx.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
// Copyright (c) 2023 William Dode. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
package webo
import (
"context"
"net/http"
"github.com/jmoiron/sqlx"
)
type TX struct {
DB *sqlx.DB
next http.Handler
}
func RequestTx(r *http.Request) *sqlx.Tx {
return r.Context().Value("webo-tx").(*sqlx.Tx)
}
func (t *TX) ServeHTTP(w http.ResponseWriter, r *http.Request) {
TxMiddleware(t.DB)(t.next).ServeHTTP(w, r)
}
func NewTx(db *sqlx.DB, h http.Handler) *TX {
c := &TX{db, h}
return c
}
func TxMiddleware(db *sqlx.DB) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log := RequestCatcherLog(r)
tx := db.MustBegin()
defer func() {
if rec := recover(); rec != nil {
log.Print("rollback")
tx.Rollback()
panic(rec)
} else {
tx.Commit()
log.Println("commit")
}
}()
ctx := context.WithValue(r.Context(), "webo-tx", tx)
r = r.WithContext(ctx)
next.ServeHTTP(w, r)
})
}
}