-
Notifications
You must be signed in to change notification settings - Fork 1
/
db_middle.go
63 lines (53 loc) · 1.23 KB
/
db_middle.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
package mid
import (
"net/http"
"runtime"
"github.com/94peter/sterna/auth"
"github.com/94peter/sterna/db"
"github.com/94peter/sterna/log"
"github.com/94peter/sterna/util"
"github.com/google/uuid"
)
type DBMidDI interface {
log.LoggerDI
db.MongoDI
}
type DBMiddle string
func NewDBMid(di DBMidDI, name string) Middle {
return &dbMiddle{
name: name,
di: di,
}
}
type dbMiddle struct {
name string
di DBMidDI
}
func (lm *dbMiddle) GetName() string {
return lm.name
}
func (am *dbMiddle) GetMiddleWare() func(f http.HandlerFunc) http.HandlerFunc {
return func(f http.HandlerFunc) http.HandlerFunc {
// one time scope setup area for middleware
return func(w http.ResponseWriter, r *http.Request) {
uuid := uuid.New().String()
l := am.di.NewLogger(uuid)
userInfo := auth.GetUserInfo(r)
userDB := ""
if userInfo != nil && userInfo.GetDB() != "" {
userDB = "ws:" + userInfo.GetDB()
}
dbclt, err := am.di.NewMongoDBClient(r.Context(), userDB)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
return
}
r = util.SetCtxKeyVal(r, db.CtxMongoKey, dbclt)
r = util.SetCtxKeyVal(r, log.CtxLogKey, l)
f(w, r)
dbclt.Close()
runtime.GC()
}
}
}