config.go 12.1 KB
Newer Older
A
astaxie 已提交
1
// Beego (http://beego.me/)
A
astaxie 已提交
2
//
A
astaxie 已提交
3
// @description beego is an open-source, high-performance web framework for the Go programming language.
A
astaxie 已提交
4
//
A
astaxie 已提交
5
// @link        http://github.com/astaxie/beego for the canonical source repository
A
astaxie 已提交
6
//
A
astaxie 已提交
7
// @license     http://github.com/astaxie/beego/blob/master/LICENSE
A
astaxie 已提交
8
//
A
astaxie 已提交
9
// @authors     astaxie
10 11 12
package beego

import (
13
	"errors"
A
astaxie 已提交
14
	"fmt"
15 16
	"html/template"
	"os"
17
	"path/filepath"
18 19
	"runtime"
	"strings"
P
Pengfei Xue 已提交
20 21

	"github.com/astaxie/beego/config"
22
	"github.com/astaxie/beego/logs"
P
Pengfei Xue 已提交
23
	"github.com/astaxie/beego/session"
24
	"github.com/astaxie/beego/utils"
25 26 27
)

var (
傅小黑 已提交
28 29 30
	BeeApp                 *App // beego application
	AppName                string
	AppPath                string
31
	workPath               string
傅小黑 已提交
32 33 34 35
	AppConfigPath          string
	StaticDir              map[string]string
	TemplateCache          map[string]*template.Template // template caching map
	StaticExtensionsToGzip []string                      // files with should be compressed with gzip (.js,.css,etc)
A
astaxie 已提交
36
	EnableHttpListen       bool
傅小黑 已提交
37 38
	HttpAddr               string
	HttpPort               int
A
astaxie 已提交
39 40
	EnableHttpTLS          bool
	HttpsPort              int
傅小黑 已提交
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
	HttpCertFile           string
	HttpKeyFile            string
	RecoverPanic           bool // flag of auto recover panic
	AutoRender             bool // flag of render template automatically
	ViewsPath              string
	RunMode                string // run mode, "dev" or "prod"
	AppConfig              config.ConfigContainer
	GlobalSessions         *session.Manager // global session mananger
	SessionOn              bool             // flag of starting session auto. default is false.
	SessionProvider        string           // default session provider, memory, mysql , redis ,etc.
	SessionName            string           // the cookie name when saving session id into cookie.
	SessionGCMaxLifetime   int64            // session gc time for auto cleaning expired session.
	SessionSavePath        string           // if use mysql/redis/file provider, define save path to connection info.
	SessionHashFunc        string           // session hash generation func.
	SessionHashKey         string           // session hash salt string.
	SessionCookieLifeTime  int              // the life time of session id in cookie.
A
astaxie 已提交
57
	SessionAutoSetCookie   bool             // auto setcookie
A
astaxie 已提交
58
	SessionDomain          string           // the cookie domain default is empty
傅小黑 已提交
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
	UseFcgi                bool
	MaxMemory              int64
	EnableGzip             bool // flag of enable gzip
	DirectoryIndex         bool // flag of display directory index. default is false.
	HttpServerTimeOut      int64
	ErrorsShow             bool   // flag of show errors in page. if true, show error and trace info in page rendered with error template.
	XSRFKEY                string // xsrf hash salt string.
	EnableXSRF             bool   // flag of enable xsrf.
	XSRFExpire             int    // the expiry of xsrf value.
	CopyRequestBody        bool   // flag of copy raw request body in context.
	TemplateLeft           string
	TemplateRight          string
	BeegoServerName        string // beego server name exported in response header.
	EnableAdmin            bool   // flag of enable admin module to log every request info.
	AdminHttpAddr          string // http server configurations for admin module.
	AdminHttpPort          int
75 76
	FlashName              string // name of the flash variable found in response header and cookie
	FlashSeperator         string // used to seperate flash key:value
A
astaxie 已提交
77
	AppConfigProvider      string // config provider
A
astaxie 已提交
78
	EnableDocs             bool   // enable generate docs & server docs API Swagger
79 80
)

A
astaxie 已提交
81
func init() {
82
	// create beego application
A
astaxie 已提交
83
	BeeApp = NewApp()
P
Pengfei Xue 已提交
84

85 86
	workPath, _ = os.Getwd()
	workPath, _ = filepath.Abs(workPath)
P
Pengfei Xue 已提交
87
	// initialize default configurations
88
	AppPath, _ = filepath.Abs(filepath.Dir(os.Args[0]))
89 90 91 92 93 94 95 96 97 98

	AppConfigPath = filepath.Join(AppPath, "conf", "app.conf")

	if workPath != AppPath {
		if utils.FileExists(AppConfigPath) {
			os.Chdir(AppPath)
		} else {
			AppConfigPath = filepath.Join(workPath, "conf", "app.conf")
		}
	}
P
Pengfei Xue 已提交
99

A
astaxie 已提交
100 101
	AppConfigProvider = "ini"

102
	StaticDir = make(map[string]string)
P
Pengfei Xue 已提交
103
	StaticDir["/static"] = "static"
104

F
Francois 已提交
105
	StaticExtensionsToGzip = []string{".css", ".js"}
P
Pengfei Xue 已提交
106

A
typo  
astaxie 已提交
107
	TemplateCache = make(map[string]*template.Template)
P
Pengfei Xue 已提交
108 109

	// set this to 0.0.0.0 to make this app available to externally
A
astaxie 已提交
110
	EnableHttpListen = true //default enable http Listen
A
astaxie 已提交
111

A
astaxie 已提交
112
	HttpAddr = ""
113
	HttpPort = 8080
P
Pengfei Xue 已提交
114

A
astaxie 已提交
115
	HttpsPort = 10443
A
astaxie 已提交
116

117
	AppName = "beego"
P
Pengfei Xue 已提交
118

119
	RunMode = "dev" //default runmod
P
Pengfei Xue 已提交
120

121
	AutoRender = true
P
Pengfei Xue 已提交
122

123
	RecoverPanic = true
P
Pengfei Xue 已提交
124

125
	ViewsPath = "views"
P
Pengfei Xue 已提交
126

127 128 129 130 131 132 133
	SessionOn = false
	SessionProvider = "memory"
	SessionName = "beegosessionID"
	SessionGCMaxLifetime = 3600
	SessionSavePath = ""
	SessionHashFunc = "sha1"
	SessionHashKey = "beegoserversessionkey"
A
astaxie 已提交
134
	SessionCookieLifeTime = 0 //set cookie default is the brower life
A
astaxie 已提交
135
	SessionAutoSetCookie = true
P
Pengfei Xue 已提交
136

137
	UseFcgi = false
P
Pengfei Xue 已提交
138

傅小黑 已提交
139
	MaxMemory = 1 << 26 //64MB
P
Pengfei Xue 已提交
140

141
	EnableGzip = false
P
Pengfei Xue 已提交
142

143
	HttpServerTimeOut = 0
P
Pengfei Xue 已提交
144

145
	ErrorsShow = true
P
Pengfei Xue 已提交
146

147 148
	XSRFKEY = "beegoxsrf"
	XSRFExpire = 0
P
Pengfei Xue 已提交
149

150 151
	TemplateLeft = "{{"
	TemplateRight = "}}"
P
Pengfei Xue 已提交
152

A
astaxie 已提交
153
	BeegoServerName = "beegoServer:" + VERSION
P
Pengfei Xue 已提交
154

155
	EnableAdmin = false
P
Pengfei Xue 已提交
156
	AdminHttpAddr = "127.0.0.1"
157
	AdminHttpPort = 8088
P
Pengfei Xue 已提交
158

159 160 161
	FlashName = "BEEGO_FLASH"
	FlashSeperator = "BEEGOFLASH"

162
	runtime.GOMAXPROCS(runtime.NumCPU())
P
Pengfei Xue 已提交
163

164 165
	// init BeeLogger
	BeeLogger = logs.NewLogger(10000)
A
astaxie 已提交
166 167 168 169
	err := BeeLogger.SetLogger("console", "")
	if err != nil {
		fmt.Println("init console log error:", err)
	}
170

A
astaxie 已提交
171
	err = ParseConfig()
P
Pengfei Xue 已提交
172
	if err != nil && !os.IsNotExist(err) {
173 174
		// for init if doesn't have app.conf will not panic
		Info(err)
P
Pengfei Xue 已提交
175
	}
176 177
}

178 179
// ParseConfig parsed default config file.
// now only support ini, next will support json.
180
func ParseConfig() (err error) {
A
astaxie 已提交
181
	AppConfig, err = config.NewConfig(AppConfigProvider, AppConfigPath)
182
	if err != nil {
183
		AppConfig = config.NewFakeConfig()
184 185
		return err
	} else {
186

A
astaxie 已提交
187
		if v, err := GetConfig("string", "HttpAddr"); err == nil {
188
			HttpAddr = v.(string)
A
astaxie 已提交
189
		}
190

A
astaxie 已提交
191
		if v, err := GetConfig("int", "HttpPort"); err == nil {
192
			HttpPort = v.(int)
193 194
		}

A
astaxie 已提交
195
		if v, err := GetConfig("bool", "EnableHttpListen"); err == nil {
196
			EnableHttpListen = v.(bool)
A
astaxie 已提交
197 198
		}

A
astaxie 已提交
199
		if maxmemory, err := GetConfig("int64", "MaxMemory"); err == nil {
200
			MaxMemory = maxmemory.(int64)
201 202
		}

A
astaxie 已提交
203
		if appname, _ := GetConfig("string", "AppName"); appname != "" {
204
			AppName = appname.(string)
205 206
		}

A
astaxie 已提交
207
		if runmode, _ := GetConfig("string", "RunMode"); runmode != "" {
208
			RunMode = runmode.(string)
209 210
		}

A
astaxie 已提交
211
		if autorender, err := GetConfig("bool", "AutoRender"); err == nil {
212
			AutoRender = autorender.(bool)
213 214
		}

A
astaxie 已提交
215
		if autorecover, err := GetConfig("bool", "RecoverPanic"); err == nil {
216
			RecoverPanic = autorecover.(bool)
217 218
		}

A
astaxie 已提交
219
		if views, _ := GetConfig("string", "ViewsPath"); views != "" {
220
			ViewsPath = views.(string)
221 222
		}

A
astaxie 已提交
223
		if sessionon, err := GetConfig("bool", "SessionOn"); err == nil {
224
			SessionOn = sessionon.(bool)
225 226
		}

A
astaxie 已提交
227
		if sessProvider, _ := GetConfig("string", "SessionProvider"); sessProvider != "" {
228
			SessionProvider = sessProvider.(string)
229 230
		}

A
astaxie 已提交
231
		if sessName, _ := GetConfig("string", "SessionName"); sessName != "" {
232
			SessionName = sessName.(string)
233 234
		}

A
astaxie 已提交
235
		if sesssavepath, _ := GetConfig("string", "SessionSavePath"); sesssavepath != "" {
236
			SessionSavePath = sesssavepath.(string)
237 238
		}

A
astaxie 已提交
239
		if sesshashfunc, _ := GetConfig("string", "SessionHashFunc"); sesshashfunc != "" {
240
			SessionHashFunc = sesshashfunc.(string)
241 242
		}

A
astaxie 已提交
243
		if sesshashkey, _ := GetConfig("string", "SessionHashKey"); sesshashkey != "" {
244
			SessionHashKey = sesshashkey.(string)
245 246
		}

A
astaxie 已提交
247
		if sessMaxLifeTime, err := GetConfig("int64", "SessionGCMaxLifetime"); err == nil && sessMaxLifeTime != 0 {
248
			SessionGCMaxLifetime = sessMaxLifeTime.(int64)
249 250
		}

A
astaxie 已提交
251
		if sesscookielifetime, err := GetConfig("int", "SessionCookieLifeTime"); err == nil && sesscookielifetime != 0 {
252
			SessionCookieLifeTime = sesscookielifetime.(int)
253 254
		}

A
astaxie 已提交
255
		if usefcgi, err := GetConfig("bool", "UseFcgi"); err == nil {
256
			UseFcgi = usefcgi.(bool)
257 258
		}

A
astaxie 已提交
259
		if enablegzip, err := GetConfig("bool", "EnableGzip"); err == nil {
260
			EnableGzip = enablegzip.(bool)
261 262
		}

A
astaxie 已提交
263
		if directoryindex, err := GetConfig("bool", "DirectoryIndex"); err == nil {
264
			DirectoryIndex = directoryindex.(bool)
265 266
		}

A
astaxie 已提交
267
		if timeout, err := GetConfig("int64", "HttpServerTimeOut"); err == nil {
268
			HttpServerTimeOut = timeout.(int64)
269 270
		}

A
astaxie 已提交
271
		if errorsshow, err := GetConfig("bool", "ErrorsShow"); err == nil {
272
			ErrorsShow = errorsshow.(bool)
273 274
		}

A
astaxie 已提交
275
		if copyrequestbody, err := GetConfig("bool", "CopyRequestBody"); err == nil {
276
			CopyRequestBody = copyrequestbody.(bool)
277 278
		}

A
astaxie 已提交
279
		if xsrfkey, _ := GetConfig("string", "XSRFKEY"); xsrfkey != "" {
280
			XSRFKEY = xsrfkey.(string)
281 282
		}

A
astaxie 已提交
283
		if enablexsrf, err := GetConfig("bool", "EnableXSRF"); err == nil {
284
			EnableXSRF = enablexsrf.(bool)
285 286
		}

A
astaxie 已提交
287
		if expire, err := GetConfig("int", "XSRFExpire"); err == nil {
288
			XSRFExpire = expire.(int)
289 290
		}

A
astaxie 已提交
291
		if tplleft, _ := GetConfig("string", "TemplateLeft"); tplleft != "" {
292
			TemplateLeft = tplleft.(string)
293 294
		}

A
astaxie 已提交
295
		if tplright, _ := GetConfig("string", "TemplateRight"); tplright != "" {
296
			TemplateRight = tplright.(string)
297 298
		}

A
astaxie 已提交
299
		if httptls, err := GetConfig("bool", "EnableHttpTLS"); err == nil {
300
			EnableHttpTLS = httptls.(bool)
A
astaxie 已提交
301 302
		}

A
astaxie 已提交
303
		if httpsport, err := GetConfig("int", "HttpsPort"); err == nil {
304
			HttpsPort = httpsport.(int)
305 306
		}

A
astaxie 已提交
307
		if certfile, _ := GetConfig("string", "HttpCertFile"); certfile != "" {
308
			HttpCertFile = certfile.(string)
309 310
		}

A
astaxie 已提交
311
		if keyfile, _ := GetConfig("string", "HttpKeyFile"); keyfile != "" {
312
			HttpKeyFile = keyfile.(string)
313 314
		}

A
astaxie 已提交
315
		if serverName, _ := GetConfig("string", "BeegoServerName"); serverName != "" {
316
			BeegoServerName = serverName.(string)
317 318
		}

A
astaxie 已提交
319
		if flashname, _ := GetConfig("string", "FlashName"); flashname != "" {
320
			FlashName = flashname.(string)
321 322
		}

A
astaxie 已提交
323
		if flashseperator, _ := GetConfig("string", "FlashSeperator"); flashseperator != "" {
324
			FlashSeperator = flashseperator.(string)
325 326
		}

A
astaxie 已提交
327
		if sd, _ := GetConfig("string", "StaticDir"); sd != "" {
328 329 330
			for k := range StaticDir {
				delete(StaticDir, k)
			}
331
			sds := strings.Fields(sd.(string))
332 333
			for _, v := range sds {
				if url2fsmap := strings.SplitN(v, ":", 2); len(url2fsmap) == 2 {
A
astaxie 已提交
334
					StaticDir["/"+strings.TrimRight(url2fsmap[0], "/")] = url2fsmap[1]
335
				} else {
A
astaxie 已提交
336
					StaticDir["/"+strings.TrimRight(url2fsmap[0], "/")] = url2fsmap[0]
337 338 339
				}
			}
		}
340

A
astaxie 已提交
341
		if sgz, _ := GetConfig("string", "StaticExtensionsToGzip"); sgz != "" {
342
			extensions := strings.Split(sgz.(string), ",")
F
Francois 已提交
343 344 345 346 347 348 349 350 351 352 353 354 355 356
			if len(extensions) > 0 {
				StaticExtensionsToGzip = []string{}
				for _, ext := range extensions {
					if len(ext) == 0 {
						continue
					}
					extWithDot := ext
					if extWithDot[:1] != "." {
						extWithDot = "." + extWithDot
					}
					StaticExtensionsToGzip = append(StaticExtensionsToGzip, extWithDot)
				}
			}
		}
357

A
astaxie 已提交
358
		if enableadmin, err := GetConfig("bool", "EnableAdmin"); err == nil {
359
			EnableAdmin = enableadmin.(bool)
360 361
		}

A
astaxie 已提交
362
		if adminhttpaddr, _ := GetConfig("string", "AdminHttpAddr"); adminhttpaddr != "" {
363
			AdminHttpAddr = adminhttpaddr.(string)
364 365
		}

A
astaxie 已提交
366
		if adminhttpport, err := GetConfig("int", "AdminHttpPort"); err == nil {
367
			AdminHttpPort = adminhttpport.(int)
368
		}
A
astaxie 已提交
369

A
astaxie 已提交
370
		if enabledocs, err := GetConfig("bool", "EnableDocs"); err == nil {
A
astaxie 已提交
371 372
			EnableDocs = enabledocs.(bool)
		}
373 374 375
	}
	return nil
}
376

A
astaxie 已提交
377 378 379 380 381 382 383 384 385 386 387 388
// Getconfig throw the Runmode
// [dev]
// name = astaixe
// IsEnable = false
// [prod]
// name = slene
// IsEnable = true
//
// usage:
// GetConfig("string", "name")
// GetConfig("bool", "IsEnable")
func GetConfig(typ, key string) (interface{}, error) {
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
	switch typ {
	case "string":
		v := AppConfig.String(RunMode + "::" + key)
		if v == "" {
			v = AppConfig.String(key)
		}
		return v, nil
	case "strings":
		v := AppConfig.Strings(RunMode + "::" + key)
		if len(v) == 0 {
			v = AppConfig.Strings(key)
		}
		return v, nil
	case "int":
		v, err := AppConfig.Int(RunMode + "::" + key)
		if err != nil || v == 0 {
			return AppConfig.Int(key)
		}
		return v, nil
	case "bool":
		v, err := AppConfig.Bool(RunMode + "::" + key)
		if err != nil {
			return AppConfig.Bool(key)
		}
		return v, nil
	case "int64":
		v, err := AppConfig.Int64(RunMode + "::" + key)
		if err != nil || v == 0 {
			return AppConfig.Int64(key)
		}
		return v, nil
	case "float":
		v, err := AppConfig.Float(RunMode + "::" + key)
		if err != nil || v == 0 {
			return AppConfig.Float(key)
		}
		return v, nil
	}
	return "", errors.New("not support type")
}