forked from Odinman/ogo
/
mux.go
306 lines (256 loc) · 6.83 KB
/
mux.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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
// Ogo
package ogo
/* {{{ import
*/
import (
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/Odinman/ogo/libs/config"
"github.com/Odinman/ogo/libs/logs"
"github.com/Odinman/ogo/utils"
)
/* }}} */
/* {{{ type Environ struct
*/
type Environ struct {
lock *sync.RWMutex
WorkPath string // working path(abs)
AppPath string // application path
ProcName string // proc name
Worker string // worker name
AppConfigPath string // config file path
RunMode string // run mode, "dev" or "prod"
AccessPath string //acces log file path
Daemonize bool // daemonize or not
EnableGzip bool // enable gzip or not
DebugLevel int // debug level
PidFile string // pidfile abs path
Port string // http port
IndentJSON bool // indent JSON
MaxMemory int64 //max memory(form-data)
Location *time.Location // location
initErr error
}
/* }}} */
/* {{{ type Mux struct
*/
type Mux struct {
env *Environ //环境参数
cfg config.ConfigContainer //配置信息
logger *logs.OLogger //debug日志记录
accessor *logs.OLogger //日志
Workers map[string]*Worker
Routes map[string]*Route
Hooks HStack
}
/* }}} */
/* {{{ func New() *Mux
*/
func New() *Mux {
return &Mux{
Workers: make(map[string]*Worker),
Routes: make(map[string]*Route),
Hooks: HStack{
preHooks: make([]OgoHook, 0),
postHooks: make([]OgoHook, 0),
},
}
}
/* }}} */
/* {{{ func (mux *Mux) PreHook(hook OgoHook)
* 正式程序之前的钩子
*/
func (mux *Mux) PreHook(hook OgoHook) {
mux.Hooks.preHooks = append(mux.Hooks.preHooks, hook)
}
/* }}} */
/* {{{ func (mux *Mux) PostHook(hook OgoHook)
* 正式程序之后的钩子
*/
func (mux *Mux) PostHook(hook OgoHook) {
mux.Hooks.postHooks = append(mux.Hooks.postHooks, hook)
}
/* }}} */
/* {{{ func (mux *Mux) NewController(c ControllerInterface, endpoint string)
* 这样做的目的是给controller设置mux(mux可多个) -- mux=multiplexer,复用器
*/
func (mux *Mux) NewController(c ControllerInterface, endpoint string) ControllerInterface {
c.New(mux, endpoint)
return c
}
/* }}} */
/* {{{ func (mux *Mux) Env(path string) *Environ, error
* 获取env变量
*/
func (mux *Mux) Env() (*Environ, error) {
if mux.env == nil {
env = &Environ{
lock: new(sync.RWMutex),
}
// default value
env.RunMode = "dev" //default runmod
env.Port = DEFAULT_PORT //default is 8001
env.Daemonize = false
env.DebugLevel = logs.LevelTrace //默认debug等级
env.IndentJSON = false
env.MaxMemory = 1 << 32 //4G
env.Location, _ = time.LoadLocation("Asia/Shanghai") //默认上海时区
workPath, _ := os.Getwd()
env.WorkPath, _ = filepath.Abs(workPath)
env.AppPath, _ = filepath.Abs(filepath.Dir(os.Args[0]))
env.ProcName = filepath.Base(os.Args[0]) //程序名字
env.Worker = strings.ToLower(env.ProcName) //worker默认为procname,小写
env.AccessPath = "logs/access.log" //默认access日志是程序目录下的logs/access.log
//默认配置文件是 conf/{ProcName}.conf
env.AppConfigPath = filepath.Join(env.AppPath, "conf", env.ProcName+".conf")
if !utils.FileExists(env.AppConfigPath) {
//不存在时指定为app.conf
tp := filepath.Join(env.AppPath, "conf", "app.conf")
if utils.FileExists(tp) {
env.AppConfigPath = tp
}
}
// pidfile depend AppPath
env.PidFile = filepath.Join(env.AppPath, "run", env.ProcName+".pid")
if env.WorkPath != env.AppPath {
//切换工作目录
os.Chdir(env.AppPath)
}
//配置文件必须存在
if !utils.FileExists(env.AppConfigPath) {
return nil, fmt.Errorf("config file not found: %s", env.AppConfigPath)
}
mux.env = env
}
return mux.env, nil
}
/* }}} */
/* {{{ func (mux *Mux) initEnv(cfg config.ConfigContainer) error
* 设置环境变量
*/
func (mux *Mux) initEnv() (err error) {
if env, err = mux.Env(); err != nil {
return err
}
if cfg, err = mux.Config(); err != nil {
return err
}
//根据配置设置环境变量
env.lock.Lock()
defer env.lock.Unlock()
// location
if tz := cfg.String("TimeZone"); tz != "" {
if loc, err := time.LoadLocation(tz); err == nil {
env.Location = loc
}
}
if port := cfg.String("Port"); port != "" {
env.Port = port
}
os.Setenv("PORT", env.Port) // pass to bind
if runmode := cfg.String("RunMode"); runmode != "" {
env.RunMode = runmode
}
if workerName := cfg.String("Worker"); workerName != "" {
env.Worker = workerName
}
if daemonize, err := cfg.Bool("Daemonize"); err == nil {
env.Daemonize = daemonize
}
if enablegzip, err := cfg.Bool("EnableGzip"); err == nil {
env.EnableGzip = enablegzip
}
if indentJson, err := cfg.Bool("IndentJson"); err == nil {
env.IndentJSON = indentJson
}
// 自定义pidfile
if pidfile := cfg.String("PidFile"); pidfile != "" {
// make sure pidfile is abs path
if filepath.IsAbs(pidfile) {
env.PidFile = pidfile
} else {
env.PidFile = filepath.Join(env.AppPath, pidfile)
}
}
//自定义access 日志位置
if apath := cfg.String("AccessPath"); apath != "" {
env.AccessPath = apath
}
if level, err := cfg.Int("DebugLevel"); err == nil {
env.DebugLevel = level
}
// logger init
if logger, err = mux.Logger(); err != nil {
return err
}
//access init
if accessor, err = mux.Accessor(); err != nil {
return err
}
return nil
}
/* }}} */
/* {{{ func (mux *Mux) Config() (config.ConfigContainer, error)
* 获取配置信息
*/
func (mux *Mux) Config() (config.ConfigContainer, error) {
if mux.cfg == nil {
if env, err := mux.Env(); err != nil {
return nil, err
} else {
cp := env.AppConfigPath
if cfg, err := config.NewConfig("ini", cp); err != nil {
return nil, err
} else {
mux.cfg = cfg
}
}
}
return mux.cfg, nil
}
/* }}} */
/* {{{ func (mux *Mux) Logger() config.LoggerContainer
*
*/
func (mux *Mux) Logger() (*logs.OLogger, error) {
if mux.logger == nil {
// init logger
logger := logs.NewLogger(204600)
var err error
if mux.env.Daemonize {
err = logger.SetLogger("file", `{"filename":"logs/debug.log"}`)
} else {
err = logger.SetLogger("console", "")
}
if err != nil {
return nil, err
}
logger.EnableFuncCallDepth(true)
logger.SetLogFuncCallDepth(4)
logger.SetLevel(mux.env.DebugLevel)
mux.logger = logger
}
return mux.logger, nil
}
/* }}} */
/* {{{ func (mux *Mux) Accessor() config.LoggerContainer
*
*/
func (mux *Mux) Accessor() (*logs.OLogger, error) {
if mux.accessor == nil {
// init logger
logger := logs.NewLogger(204600)
var err error
err = logger.SetLogger("access", fmt.Sprintf(`{"filename":"%s"}`, mux.env.AccessPath))
if err != nil {
return nil, err
}
mux.accessor = logger
}
return mux.accessor, nil
}
/* }}} */