config.go 11.9 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 187 188

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

191 192
		if v, err := getConfig("int", "HttpPort"); err == nil {
			HttpPort = v.(int)
193 194
		}

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

199 200
		if maxmemory, err := getConfig("int64", "MaxMemory"); err == nil {
			MaxMemory = maxmemory.(int64)
201 202
		}

203 204
		if appname, _ := getConfig("string", "AppName"); appname != "" {
			AppName = appname.(string)
205 206
		}

207 208
		if runmode, _ := getConfig("string", "RunMode"); runmode != "" {
			RunMode = runmode.(string)
209 210
		}

211 212
		if autorender, err := getConfig("bool", "AutoRender"); err == nil {
			AutoRender = autorender.(bool)
213 214
		}

215 216
		if autorecover, err := getConfig("bool", "RecoverPanic"); err == nil {
			RecoverPanic = autorecover.(bool)
217 218
		}

219 220
		if views, _ := getConfig("string", "ViewsPath"); views != "" {
			ViewsPath = views.(string)
221 222
		}

223 224
		if sessionon, err := getConfig("bool", "SessionOn"); err == nil {
			SessionOn = sessionon.(bool)
225 226
		}

227 228
		if sessProvider, _ := getConfig("string", "SessionProvider"); sessProvider != "" {
			SessionProvider = sessProvider.(string)
229 230
		}

231 232
		if sessName, _ := getConfig("string", "SessionName"); sessName != "" {
			SessionName = sessName.(string)
233 234
		}

235 236
		if sesssavepath, _ := getConfig("string", "SessionSavePath"); sesssavepath != "" {
			SessionSavePath = sesssavepath.(string)
237 238
		}

239 240
		if sesshashfunc, _ := getConfig("string", "SessionHashFunc"); sesshashfunc != "" {
			SessionHashFunc = sesshashfunc.(string)
241 242
		}

243 244
		if sesshashkey, _ := getConfig("string", "SessionHashKey"); sesshashkey != "" {
			SessionHashKey = sesshashkey.(string)
245 246
		}

247 248
		if sessMaxLifeTime, err := getConfig("int64", "SessionGCMaxLifetime"); err == nil && sessMaxLifeTime != 0 {
			SessionGCMaxLifetime = sessMaxLifeTime.(int64)
249 250
		}

251 252
		if sesscookielifetime, err := getConfig("int", "SessionCookieLifeTime"); err == nil && sesscookielifetime != 0 {
			SessionCookieLifeTime = sesscookielifetime.(int)
253 254
		}

255 256
		if usefcgi, err := getConfig("bool", "UseFcgi"); err == nil {
			UseFcgi = usefcgi.(bool)
257 258
		}

259 260
		if enablegzip, err := getConfig("bool", "EnableGzip"); err == nil {
			EnableGzip = enablegzip.(bool)
261 262
		}

263 264
		if directoryindex, err := getConfig("bool", "DirectoryIndex"); err == nil {
			DirectoryIndex = directoryindex.(bool)
265 266
		}

267 268
		if timeout, err := getConfig("int64", "HttpServerTimeOut"); err == nil {
			HttpServerTimeOut = timeout.(int64)
269 270
		}

271 272
		if errorsshow, err := getConfig("bool", "ErrorsShow"); err == nil {
			ErrorsShow = errorsshow.(bool)
273 274
		}

275 276
		if copyrequestbody, err := getConfig("bool", "CopyRequestBody"); err == nil {
			CopyRequestBody = copyrequestbody.(bool)
277 278
		}

279 280
		if xsrfkey, _ := getConfig("string", "XSRFKEY"); xsrfkey != "" {
			XSRFKEY = xsrfkey.(string)
281 282
		}

283 284
		if enablexsrf, err := getConfig("bool", "EnableXSRF"); err == nil {
			EnableXSRF = enablexsrf.(bool)
285 286
		}

287 288
		if expire, err := getConfig("int", "XSRFExpire"); err == nil {
			XSRFExpire = expire.(int)
289 290
		}

291 292
		if tplleft, _ := getConfig("string", "TemplateLeft"); tplleft != "" {
			TemplateLeft = tplleft.(string)
293 294
		}

295 296
		if tplright, _ := getConfig("string", "TemplateRight"); tplright != "" {
			TemplateRight = tplright.(string)
297 298
		}

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

303 304
		if httpsport, err := getConfig("int", "HttpsPort"); err == nil {
			HttpsPort = httpsport.(int)
305 306
		}

307 308
		if certfile, _ := getConfig("string", "HttpCertFile"); certfile != "" {
			HttpCertFile = certfile.(string)
309 310
		}

311 312
		if keyfile, _ := getConfig("string", "HttpKeyFile"); keyfile != "" {
			HttpKeyFile = keyfile.(string)
313 314
		}

315 316
		if serverName, _ := getConfig("string", "BeegoServerName"); serverName != "" {
			BeegoServerName = serverName.(string)
317 318
		}

319 320
		if flashname, _ := getConfig("string", "FlashName"); flashname != "" {
			FlashName = flashname.(string)
321 322
		}

323 324
		if flashseperator, _ := getConfig("string", "FlashSeperator"); flashseperator != "" {
			FlashSeperator = flashseperator.(string)
325 326
		}

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

341 342
		if sgz, _ := getConfig("string", "StaticExtensionsToGzip"); sgz != "" {
			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

358 359
		if enableadmin, err := getConfig("bool", "EnableAdmin"); err == nil {
			EnableAdmin = enableadmin.(bool)
360 361
		}

362 363
		if adminhttpaddr, _ := getConfig("string", "AdminHttpAddr"); adminhttpaddr != "" {
			AdminHttpAddr = adminhttpaddr.(string)
364 365
		}

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

		if enabledocs, err := getConfig("bool", "EnableDocs"); err == nil {
			EnableDocs = enabledocs.(bool)
		}
373 374 375
	}
	return nil
}
376 377 378 379 380 381 382 383 384 385 386 387 388 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

func getConfig(typ, key string) (interface{}, error) {
	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")
}