-
Notifications
You must be signed in to change notification settings - Fork 13
/
container.go
132 lines (101 loc) · 2.5 KB
/
container.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
package service
import (
"context"
"fmt"
"github.com/gin-gonic/gin"
"github.com/sarulabs/di"
"github.com/coretrix/hitrix/service/component/app"
)
type key int
const (
GinKey key = iota
RequestBodyKey
)
var container di.Container
var servicesDefinitionsRequestList []*DefinitionRequest
type DefinitionGlobal struct {
Name string
Script bool
Build func(ctn di.Container) (interface{}, error)
Close func(obj interface{}) error
Flags func(registry *app.FlagsRegistry)
}
type DefinitionRequest struct {
Name string
Build func(ctn *gin.Context) (interface{}, error)
}
func SetContainer(c di.Container) {
if container != nil {
_ = container.Delete()
}
container = c
}
func SetRequestServices(servicesDefinitionsRequest []*DefinitionRequest) {
servicesDefinitionsRequestList = servicesDefinitionsRequest
}
func HasService(key string) bool {
if container == nil {
return false
}
_, has := container.Definitions()[key]
return has
}
func GetServiceOptional(key string) (service interface{}, has bool) {
return getServiceOptional(container, key)
}
func GetServiceRequired(key string) interface{} {
return getServiceRequired(container, key)
}
func GetServiceForRequestRequired(ctx context.Context, key string) interface{} {
return GetServiceFromRequest(ctx, key)
}
func getServiceSafe(ctn di.Container, key string) (service interface{}, has bool, err error) {
service, err = ctn.SafeGet(key)
if err == nil {
return service, true, nil
}
_, has = ctn.Definitions()[key]
if !has {
return nil, false, nil
}
return nil, true, err
}
func getServiceOptional(ctn di.Container, key string) (service interface{}, has bool) {
service, has, err := getServiceSafe(ctn, key)
if err != nil {
panic(err)
}
return service, has
}
func getServiceRequired(ctn di.Container, key string) interface{} {
service, has, err := getServiceSafe(ctn, key)
if err != nil {
panic(err)
} else if !has {
panic(fmt.Errorf("missing service " + key))
}
return service
}
func GetServiceFromRequest(ctx context.Context, key string) interface{} {
c := GinFromContext(ctx)
requestService, has := c.Get(key)
if !has {
var err error
for _, s := range servicesDefinitionsRequestList {
if s.Name == key {
requestService, err = s.Build(c)
if err != nil {
panic(err)
}
}
}
c.Set(key, requestService)
}
if requestService == nil {
panic("not defined service " + key)
}
return requestService
}
func GinFromContext(ctx context.Context) *gin.Context {
return ctx.Value(GinKey).(*gin.Context)
}