/
builder.go
63 lines (52 loc) · 1.32 KB
/
builder.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 ginx
import (
"github.com/gin-gonic/gin"
)
type ServerBuilder struct {
preRuns []ServerConfigureFunc
initors []ServerConfigureFunc
Options *ServerOptions
// 只在程序启动过程中进行操作,以保证协程安全
Items map[string]any
}
func NewServerBuilder() *ServerBuilder {
return &ServerBuilder{
preRuns: make([]ServerConfigureFunc, 0),
initors: make([]ServerConfigureFunc, 0),
Options: &ServerOptions{
Port: 5000,
},
Items: make(map[string]any),
}
}
// PreConfigure 配置服务,该方法参数在App.Run中、gin.Run之前运行
func (b *ServerBuilder) PreConfigure(action ServerConfigureFunc) *ServerBuilder {
b.preRuns = append(b.preRuns, action)
return b
}
// Configure 配置服务,该方法参数在App.Run中、gin.Run之前运行
func (b *ServerBuilder) Configure(action ServerConfigureFunc) *ServerBuilder {
b.initors = append(b.initors, action)
return b
}
func (b *ServerBuilder) Add(fun func(b *ServerBuilder)) *ServerBuilder {
fun(b)
return b
}
func (b *ServerBuilder) Build() (*Server, error) {
g := gin.Default()
server := NewServer(g, b.Options)
for _, action := range b.preRuns {
err := action(server)
if err != nil {
return nil, err
}
}
for _, action := range b.initors {
err := action(server)
if err != nil {
return nil, err
}
}
return server, nil
}