-
Notifications
You must be signed in to change notification settings - Fork 0
/
decorator.go
65 lines (54 loc) · 1.6 KB
/
decorator.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
package handler_decorator
import (
"context"
"net/http"
nrcontext "github.com/best-expendables/newrelic-context"
"github.com/go-redis/redis"
"github.com/jinzhu/gorm"
)
type HandlerCreatorFunc func(decorator HandlerDecorator) http.HandlerFunc
type HandlerDecorator struct {
db *gorm.DB
redisClient *redis.Client
}
func (b *HandlerDecorator) cloneWithContext(ctx context.Context) HandlerDecorator {
clone := HandlerDecorator{}
if b.db != nil {
clone.db = nrcontext.SetTxnToGorm(ctx, b.db)
}
if b.redisClient != nil {
clone.redisClient = nrcontext.WrapRedisClient(ctx, b.redisClient)
}
return clone
}
func (b HandlerDecorator) GetDB() *gorm.DB {
return b.db
}
func (b HandlerDecorator) GetRedisClient() *redis.Client {
return b.redisClient
}
type Option func(h *HandlerDecorator) *HandlerDecorator
func AddRedisToDecorator(r *redis.Client) func(h *HandlerDecorator) *HandlerDecorator {
return func(h *HandlerDecorator) *HandlerDecorator {
h.redisClient = r
return h
}
}
func AddDBToDecorator(db *gorm.DB) func(h *HandlerDecorator) *HandlerDecorator {
return func(h *HandlerDecorator) *HandlerDecorator {
h.db = db
return h
}
}
func NewHandlerDecorator(options ...Option) *HandlerDecorator {
baseHandler := &HandlerDecorator{}
for i := range options {
options[i](baseHandler)
}
return baseHandler
}
func (b *HandlerDecorator) NewRelicDecorate(handlerCreatorFunc func(decorator HandlerDecorator) http.HandlerFunc) http.HandlerFunc {
return func(writer http.ResponseWriter, request *http.Request) {
handlerCreatorFunc(b.cloneWithContext(request.Context())).ServeHTTP(writer, request)
}
}