config.go 13.4 KB
Newer Older
A
astaxie 已提交
1
// Copyright 2014 beego Author. All Rights Reserved.
A
astaxie 已提交
2
//
A
astaxie 已提交
3 4 5
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
A
astaxie 已提交
6
//
A
astaxie 已提交
7
//      http://www.apache.org/licenses/LICENSE-2.0
A
astaxie 已提交
8
//
A
astaxie 已提交
9 10 11 12 13 14
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

15 16 17
package beego

import (
A
astaxie 已提交
18
	"fmt"
19 20
	"html/template"
	"os"
21
	"path/filepath"
22 23
	"runtime"
	"strings"
P
Pengfei Xue 已提交
24 25

	"github.com/astaxie/beego/config"
26
	"github.com/astaxie/beego/logs"
P
Pengfei Xue 已提交
27
	"github.com/astaxie/beego/session"
28
	"github.com/astaxie/beego/utils"
29 30 31
)

var (
傅小黑 已提交
32 33 34
	BeeApp                 *App // beego application
	AppName                string
	AppPath                string
35
	workPath               string
傅小黑 已提交
36 37 38 39
	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 已提交
40
	EnableHttpListen       bool
傅小黑 已提交
41 42
	HttpAddr               string
	HttpPort               int
A
astaxie 已提交
43 44
	EnableHttpTLS          bool
	HttpsPort              int
傅小黑 已提交
45 46 47 48 49
	HttpCertFile           string
	HttpKeyFile            string
	RecoverPanic           bool // flag of auto recover panic
	AutoRender             bool // flag of render template automatically
	ViewsPath              string
A
astaxie 已提交
50 51
	AppConfig              *beegoAppConfig
	RunMode                string           // run mode, "dev" or "prod"
傅小黑 已提交
52 53 54 55 56 57 58 59 60
	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 已提交
61
	SessionAutoSetCookie   bool             // auto setcookie
A
astaxie 已提交
62
	SessionDomain          string           // the cookie domain default is empty
傅小黑 已提交
63
	UseFcgi                bool
64
	UseStdIo               bool
傅小黑 已提交
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
	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
80 81
	FlashName              string // name of the flash variable found in response header and cookie
	FlashSeperator         string // used to seperate flash key:value
A
astaxie 已提交
82
	AppConfigProvider      string // config provider
A
astaxie 已提交
83
	EnableDocs             bool   // enable generate docs & server docs API Swagger
A
astaxie 已提交
84
	RouterCaseSensitive    bool   // router case sensitive default is true
85 86
)

B
Bill Davis 已提交
87 88 89
type beegoAppConfig struct {
	innerConfig config.ConfigContainer
}
A
astaxie 已提交
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

func newAppConfig(AppConfigProvider, AppConfigPath string) *beegoAppConfig {
	ac, err := config.NewConfig(AppConfigProvider, AppConfigPath)
	if err != nil {
		ac = config.NewFakeConfig()
	}
	rac := &beegoAppConfig{ac}
	return rac
}

func (b *beegoAppConfig) Set(key, val string) error {
	return b.innerConfig.Set(key, val)
}

func (b *beegoAppConfig) String(key string) string {
	v := b.innerConfig.String(RunMode + "::" + key)
	if v == "" {
		return b.innerConfig.String(key)
	}
	return v
}

func (b *beegoAppConfig) Strings(key string) []string {
	v := b.innerConfig.Strings(RunMode + "::" + key)
	if len(v) == 0 {
		return b.innerConfig.Strings(key)
	}
	return v
}

func (b *beegoAppConfig) Int(key string) (int, error) {
	v, err := b.innerConfig.Int(RunMode + "::" + key)
	if err != nil {
		return b.innerConfig.Int(key)
	}
	return v, nil
}

func (b *beegoAppConfig) Int64(key string) (int64, error) {
	v, err := b.innerConfig.Int64(RunMode + "::" + key)
	if err != nil {
		return b.innerConfig.Int64(key)
	}
	return v, nil
}

func (b *beegoAppConfig) Bool(key string) (bool, error) {
	v, err := b.innerConfig.Bool(RunMode + "::" + key)
	if err != nil {
		return b.innerConfig.Bool(key)
	}
	return v, nil
}

func (b *beegoAppConfig) Float(key string) (float64, error) {
	v, err := b.innerConfig.Float(RunMode + "::" + key)
	if err != nil {
		return b.innerConfig.Float(key)
	}
	return v, nil
}

func (b *beegoAppConfig) DefaultString(key string, defaultval string) string {
	return b.innerConfig.DefaultString(key, defaultval)
}

func (b *beegoAppConfig) DefaultStrings(key string, defaultval []string) []string {
	return b.innerConfig.DefaultStrings(key, defaultval)
}

func (b *beegoAppConfig) DefaultInt(key string, defaultval int) int {
	return b.innerConfig.DefaultInt(key, defaultval)
}

func (b *beegoAppConfig) DefaultInt64(key string, defaultval int64) int64 {
	return b.innerConfig.DefaultInt64(key, defaultval)
}

func (b *beegoAppConfig) DefaultBool(key string, defaultval bool) bool {
	return b.innerConfig.DefaultBool(key, defaultval)
}

func (b *beegoAppConfig) DefaultFloat(key string, defaultval float64) float64 {
	return b.innerConfig.DefaultFloat(key, defaultval)
}

func (b *beegoAppConfig) DIY(key string) (interface{}, error) {
	return b.innerConfig.DIY(key)
}

func (b *beegoAppConfig) GetSection(section string) (map[string]string, error) {
	return b.innerConfig.GetSection(section)
}

func (b *beegoAppConfig) SaveConfigFile(filename string) error {
	return b.innerConfig.SaveConfigFile(filename)
}

A
astaxie 已提交
188
func init() {
189
	// create beego application
A
astaxie 已提交
190
	BeeApp = NewApp()
P
Pengfei Xue 已提交
191

192 193
	workPath, _ = os.Getwd()
	workPath, _ = filepath.Abs(workPath)
P
Pengfei Xue 已提交
194
	// initialize default configurations
195
	AppPath, _ = filepath.Abs(filepath.Dir(os.Args[0]))
196 197 198 199 200 201 202 203 204 205

	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 已提交
206

A
astaxie 已提交
207 208
	AppConfigProvider = "ini"

209
	StaticDir = make(map[string]string)
P
Pengfei Xue 已提交
210
	StaticDir["/static"] = "static"
211

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

A
typo  
astaxie 已提交
214
	TemplateCache = make(map[string]*template.Template)
P
Pengfei Xue 已提交
215 216

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

A
astaxie 已提交
219
	HttpAddr = ""
220
	HttpPort = 8080
P
Pengfei Xue 已提交
221

A
astaxie 已提交
222
	HttpsPort = 10443
A
astaxie 已提交
223

224
	AppName = "beego"
P
Pengfei Xue 已提交
225

226
	RunMode = "dev" //default runmod
P
Pengfei Xue 已提交
227

228
	AutoRender = true
P
Pengfei Xue 已提交
229

230
	RecoverPanic = true
P
Pengfei Xue 已提交
231

232
	ViewsPath = "views"
P
Pengfei Xue 已提交
233

234 235 236 237 238 239 240
	SessionOn = false
	SessionProvider = "memory"
	SessionName = "beegosessionID"
	SessionGCMaxLifetime = 3600
	SessionSavePath = ""
	SessionHashFunc = "sha1"
	SessionHashKey = "beegoserversessionkey"
A
astaxie 已提交
241
	SessionCookieLifeTime = 0 //set cookie default is the brower life
A
astaxie 已提交
242
	SessionAutoSetCookie = true
P
Pengfei Xue 已提交
243

244
	UseFcgi = false
245
	UseStdIo = false
P
Pengfei Xue 已提交
246

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

249
	EnableGzip = false
P
Pengfei Xue 已提交
250

251
	HttpServerTimeOut = 0
P
Pengfei Xue 已提交
252

253
	ErrorsShow = true
P
Pengfei Xue 已提交
254

255 256
	XSRFKEY = "beegoxsrf"
	XSRFExpire = 0
P
Pengfei Xue 已提交
257

258 259
	TemplateLeft = "{{"
	TemplateRight = "}}"
P
Pengfei Xue 已提交
260

A
astaxie 已提交
261
	BeegoServerName = "beegoServer:" + VERSION
P
Pengfei Xue 已提交
262

263
	EnableAdmin = false
P
Pengfei Xue 已提交
264
	AdminHttpAddr = "127.0.0.1"
265
	AdminHttpPort = 8088
P
Pengfei Xue 已提交
266

267 268 269
	FlashName = "BEEGO_FLASH"
	FlashSeperator = "BEEGOFLASH"

A
astaxie 已提交
270 271
	RouterCaseSensitive = true

272
	runtime.GOMAXPROCS(runtime.NumCPU())
P
Pengfei Xue 已提交
273

274 275
	// init BeeLogger
	BeeLogger = logs.NewLogger(10000)
A
astaxie 已提交
276 277 278 279
	err := BeeLogger.SetLogger("console", "")
	if err != nil {
		fmt.Println("init console log error:", err)
	}
280

A
astaxie 已提交
281
	err = ParseConfig()
P
Pengfei Xue 已提交
282
	if err != nil && !os.IsNotExist(err) {
283 284
		// for init if doesn't have app.conf will not panic
		Info(err)
P
Pengfei Xue 已提交
285
	}
286 287
}

288 289
// ParseConfig parsed default config file.
// now only support ini, next will support json.
290
func ParseConfig() (err error) {
A
astaxie 已提交
291
	AppConfig = newAppConfig(AppConfigProvider, AppConfigPath)
292

B
Bill Davis 已提交
293
	envRunMode := os.Getenv("BEEGO_RUNMODE")
A
astaxie 已提交
294
	// set the runmode first
B
Bill Davis 已提交
295 296
	if envRunMode != "" {
		RunMode = envRunMode
297
	} else if runmode := AppConfig.String("RunMode"); runmode != "" {
A
astaxie 已提交
298 299
		RunMode = runmode
	}
300

A
astaxie 已提交
301
	HttpAddr = AppConfig.String("HttpAddr")
302

A
astaxie 已提交
303 304 305
	if v, err := AppConfig.Int("HttpPort"); err == nil {
		HttpPort = v
	}
A
astaxie 已提交
306

A
astaxie 已提交
307 308 309
	if v, err := AppConfig.Bool("EnableHttpListen"); err == nil {
		EnableHttpListen = v
	}
310

A
astaxie 已提交
311 312 313
	if maxmemory, err := AppConfig.Int64("MaxMemory"); err == nil {
		MaxMemory = maxmemory
	}
314

A
astaxie 已提交
315 316 317
	if appname := AppConfig.String("AppName"); appname != "" {
		AppName = appname
	}
318

A
astaxie 已提交
319 320 321
	if autorender, err := AppConfig.Bool("AutoRender"); err == nil {
		AutoRender = autorender
	}
322

A
astaxie 已提交
323 324 325
	if autorecover, err := AppConfig.Bool("RecoverPanic"); err == nil {
		RecoverPanic = autorecover
	}
326

A
astaxie 已提交
327 328 329
	if views := AppConfig.String("ViewsPath"); views != "" {
		ViewsPath = views
	}
330

A
astaxie 已提交
331 332 333
	if sessionon, err := AppConfig.Bool("SessionOn"); err == nil {
		SessionOn = sessionon
	}
334

A
astaxie 已提交
335 336 337
	if sessProvider := AppConfig.String("SessionProvider"); sessProvider != "" {
		SessionProvider = sessProvider
	}
338

A
astaxie 已提交
339 340 341
	if sessName := AppConfig.String("SessionName"); sessName != "" {
		SessionName = sessName
	}
342

A
astaxie 已提交
343 344 345
	if sesssavepath := AppConfig.String("SessionSavePath"); sesssavepath != "" {
		SessionSavePath = sesssavepath
	}
346

A
astaxie 已提交
347 348 349
	if sesshashfunc := AppConfig.String("SessionHashFunc"); sesshashfunc != "" {
		SessionHashFunc = sesshashfunc
	}
350

A
astaxie 已提交
351 352 353
	if sesshashkey := AppConfig.String("SessionHashKey"); sesshashkey != "" {
		SessionHashKey = sesshashkey
	}
354

A
astaxie 已提交
355 356 357
	if sessMaxLifeTime, err := AppConfig.Int64("SessionGCMaxLifetime"); err == nil && sessMaxLifeTime != 0 {
		SessionGCMaxLifetime = sessMaxLifeTime
	}
358

A
astaxie 已提交
359 360 361
	if sesscookielifetime, err := AppConfig.Int("SessionCookieLifeTime"); err == nil && sesscookielifetime != 0 {
		SessionCookieLifeTime = sesscookielifetime
	}
362

A
astaxie 已提交
363 364 365
	if usefcgi, err := AppConfig.Bool("UseFcgi"); err == nil {
		UseFcgi = usefcgi
	}
366

A
astaxie 已提交
367 368 369
	if enablegzip, err := AppConfig.Bool("EnableGzip"); err == nil {
		EnableGzip = enablegzip
	}
370

A
astaxie 已提交
371 372 373
	if directoryindex, err := AppConfig.Bool("DirectoryIndex"); err == nil {
		DirectoryIndex = directoryindex
	}
374

A
astaxie 已提交
375 376 377
	if timeout, err := AppConfig.Int64("HttpServerTimeOut"); err == nil {
		HttpServerTimeOut = timeout
	}
378

A
astaxie 已提交
379 380 381
	if errorsshow, err := AppConfig.Bool("ErrorsShow"); err == nil {
		ErrorsShow = errorsshow
	}
382

A
astaxie 已提交
383 384 385
	if copyrequestbody, err := AppConfig.Bool("CopyRequestBody"); err == nil {
		CopyRequestBody = copyrequestbody
	}
386

A
astaxie 已提交
387 388 389
	if xsrfkey := AppConfig.String("XSRFKEY"); xsrfkey != "" {
		XSRFKEY = xsrfkey
	}
390

A
astaxie 已提交
391 392 393
	if enablexsrf, err := AppConfig.Bool("EnableXSRF"); err == nil {
		EnableXSRF = enablexsrf
	}
394

A
astaxie 已提交
395 396 397
	if expire, err := AppConfig.Int("XSRFExpire"); err == nil {
		XSRFExpire = expire
	}
398

A
astaxie 已提交
399 400 401
	if tplleft := AppConfig.String("TemplateLeft"); tplleft != "" {
		TemplateLeft = tplleft
	}
402

A
astaxie 已提交
403 404 405
	if tplright := AppConfig.String("TemplateRight"); tplright != "" {
		TemplateRight = tplright
	}
406

A
astaxie 已提交
407 408 409
	if httptls, err := AppConfig.Bool("EnableHttpTLS"); err == nil {
		EnableHttpTLS = httptls
	}
A
astaxie 已提交
410

A
astaxie 已提交
411 412 413
	if httpsport, err := AppConfig.Int("HttpsPort"); err == nil {
		HttpsPort = httpsport
	}
414

A
astaxie 已提交
415 416 417
	if certfile := AppConfig.String("HttpCertFile"); certfile != "" {
		HttpCertFile = certfile
	}
418

A
astaxie 已提交
419 420 421
	if keyfile := AppConfig.String("HttpKeyFile"); keyfile != "" {
		HttpKeyFile = keyfile
	}
422

A
astaxie 已提交
423 424 425
	if serverName := AppConfig.String("BeegoServerName"); serverName != "" {
		BeegoServerName = serverName
	}
426

A
astaxie 已提交
427 428 429
	if flashname := AppConfig.String("FlashName"); flashname != "" {
		FlashName = flashname
	}
430

A
astaxie 已提交
431 432 433
	if flashseperator := AppConfig.String("FlashSeperator"); flashseperator != "" {
		FlashSeperator = flashseperator
	}
434

A
astaxie 已提交
435 436 437 438 439 440 441 442 443 444
	if sd := AppConfig.String("StaticDir"); sd != "" {
		for k := range StaticDir {
			delete(StaticDir, k)
		}
		sds := strings.Fields(sd)
		for _, v := range sds {
			if url2fsmap := strings.SplitN(v, ":", 2); len(url2fsmap) == 2 {
				StaticDir["/"+strings.TrimRight(url2fsmap[0], "/")] = url2fsmap[1]
			} else {
				StaticDir["/"+strings.TrimRight(url2fsmap[0], "/")] = url2fsmap[0]
445 446
			}
		}
A
astaxie 已提交
447
	}
448

A
astaxie 已提交
449 450 451 452 453 454 455
	if sgz := AppConfig.String("StaticExtensionsToGzip"); sgz != "" {
		extensions := strings.Split(sgz, ",")
		if len(extensions) > 0 {
			StaticExtensionsToGzip = []string{}
			for _, ext := range extensions {
				if len(ext) == 0 {
					continue
F
Francois 已提交
456
				}
A
astaxie 已提交
457 458 459 460 461
				extWithDot := ext
				if extWithDot[:1] != "." {
					extWithDot = "." + extWithDot
				}
				StaticExtensionsToGzip = append(StaticExtensionsToGzip, extWithDot)
F
Francois 已提交
462 463
			}
		}
A
astaxie 已提交
464
	}
465

A
astaxie 已提交
466 467 468
	if enableadmin, err := AppConfig.Bool("EnableAdmin"); err == nil {
		EnableAdmin = enableadmin
	}
469

A
astaxie 已提交
470 471 472
	if adminhttpaddr := AppConfig.String("AdminHttpAddr"); adminhttpaddr != "" {
		AdminHttpAddr = adminhttpaddr
	}
A
astaxie 已提交
473

A
astaxie 已提交
474 475 476
	if adminhttpport, err := AppConfig.Int("AdminHttpPort"); err == nil {
		AdminHttpPort = adminhttpport
	}
A
astaxie 已提交
477

A
astaxie 已提交
478 479
	if enabledocs, err := AppConfig.Bool("EnableDocs"); err == nil {
		EnableDocs = enabledocs
480
	}
481

A
astaxie 已提交
482 483
	if casesensitive, err := AppConfig.Bool("RouterCaseSensitive"); err == nil {
		RouterCaseSensitive = casesensitive
484
	}
A
astaxie 已提交
485
	return nil
486
}