/
context.go
73 lines (62 loc) · 1.22 KB
/
context.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
package ctxs
import (
"bytes"
"io/ioutil"
"net/http"
"sync"
"github.com/champly/hercules/ctxs/component"
"github.com/gin-gonic/gin"
"gopkg.in/go-playground/validator.v9"
)
const (
ServerTypeHTTP = "http"
ServerTypeCron = "cron"
ServerTypeMQ = "mq"
)
type Context struct {
*herContext
Log ILog
ToolBox component.IToolBox
Type string
}
var (
contextPool *sync.Pool
validate *validator.Validate
)
func init() {
contextPool = &sync.Pool{
New: func() interface{} {
return &Context{
ToolBox: component.NewToolBox(),
}
},
}
validate = validator.New()
}
func GetContext(c *gin.Context) *Context {
ctx := contextPool.Get().(*Context)
ctx.herContext = NewHerContext(c)
ctx.Log = NewLogger()
return ctx
}
func GetCronContext() *Context {
ctx := contextPool.Get().(*Context)
ctx.Log = NewLogger()
return ctx
}
func GetMQContext(msg string) *Context {
ctx := contextPool.Get().(*Context)
ctx.herContext = NewHerContext(&gin.Context{
Request: &http.Request{
Body: ioutil.NopCloser(bytes.NewBuffer([]byte(msg))),
},
})
ctx.Log = NewLogger()
return ctx
}
func (c *Context) Put() {
contextPool.Put(c)
}
func (c *Context) CheckStruct(data interface{}) error {
return validate.Struct(data)
}