-
Notifications
You must be signed in to change notification settings - Fork 0
/
context.go
80 lines (66 loc) · 2.11 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
74
75
76
77
78
79
80
package gbase
import (
gcontext "context"
"strconv"
"sync/atomic"
"go.uber.org/zap"
"github.com/cjey/gbase/context"
)
// type alias
type (
Context = context.Context
)
// SessionNameGenerator used to generate session name automatically,
// you can replace it
var SessionNameGenerator = func() func() string {
var counter uint64
return func() string {
// return bootid related sequential name
const h = "000000000000"
var seq = atomic.AddUint64(&counter, 1)
var s = strconv.FormatUint(seq, 10)
return BootID[:24] + h[:12-len(s)] + s
}
}()
// SimpleContext return new context without name
func SimpleContext() Context {
return context.Simple()
}
// SessionContext return new context use auto session name that
// generated by SessionNameGenerator
func SessionContext() Context {
return NamedContext(SessionNameGenerator())
}
// NamedContext return new context use specified session name
func NamedContext(name string) Context {
return context.New(gcontext.Background(), context.NewEnv(),
context.NewLogger(name, "", zap.S(), nil, nil),
)
}
// ToSimpleContext return new context use specified official context without name
func ToSimpleContext(gctx gcontext.Context) Context {
return ToNamedContext(gctx, "")
}
// ToSessionContext return new context use specified official context with auto session name that
// generated by SessionNameGenerator
func ToSessionContext(gctx gcontext.Context) Context {
return ToNamedContext(gctx, SessionNameGenerator())
}
// ToNamedContext return new context use specified official context and name
func ToNamedContext(gctx gcontext.Context, name string) Context {
return context.New(gctx, context.NewEnv(),
context.NewLogger(name, "", zap.S(), nil, nil),
)
}
// SetSession use to set real session name
func SetSession(ctx Context, session string) {
context.SetSession(ctx, session)
}
// GetSession use to get session name if it has real session, otherwise return context name instead
func GetSession(ctx Context) string {
return context.GetSession(ctx)
}
// GetRealSession use to get real session name
func GetRealSession(ctx Context) string {
return context.GetRealSession(ctx)
}