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 18 19
package beego

import (
	"html/template"
	"os"
20
	"path/filepath"
21
	"strings"
P
Pengfei Xue 已提交
22 23 24

	"github.com/astaxie/beego/config"
	"github.com/astaxie/beego/session"
25
	"github.com/astaxie/beego/utils"
26 27
)

A
astaxie 已提交
28 29 30
type BeegoConfig struct {
	AppName             string //Application name
	RunMode             string //Running Mode: dev | prod
31
	RouterCaseSensitive bool
A
astaxie 已提交
32 33 34 35 36 37 38 39 40
	ServerName          string
	RecoverPanic        bool
	CopyRequestBody     bool
	EnableGzip          bool
	MaxMemory           int64
	EnableErrorsShow    bool
	Listen              Listen
	WebConfig           WebConfig
	Log                 LogConfig
A
astaxie 已提交
41 42
}

A
astaxie 已提交
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
type Listen struct {
	Graceful      bool // Graceful means use graceful module to start the server
	ServerTimeOut int64
	ListenTCP4    bool
	HTTPEnable    bool
	HTTPAddr      string
	HTTPPort      int
	HTTPSEnable   bool
	HTTPSAddr     string
	HTTPSPort     int
	HTTPSCertFile string
	HTTPSKeyFile  string
	AdminEnable   bool
	AdminAddr     string
	AdminPort     int
	EnableFcgi    bool
	EnableStdIo   bool // EnableStdIo works with EnableFcgi Use FCGI via standard I/O
A
astaxie 已提交
60 61
}

A
astaxie 已提交
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
type WebConfig struct {
	AutoRender             bool
	EnableDocs             bool
	FlashName              string
	FlashSeperator         string
	DirectoryIndex         bool
	StaticDir              map[string]string
	StaticExtensionsToGzip []string
	TemplateLeft           string
	TemplateRight          string
	ViewsPath              string
	EnableXSRF             bool
	XSRFKEY                string
	XSRFExpire             int
	Session                SessionConfig
A
astaxie 已提交
77 78
}

A
astaxie 已提交
79 80 81 82 83 84 85 86 87
type SessionConfig struct {
	SessionOn             bool
	SessionProvider       string
	SessionName           string
	SessionGCMaxLifetime  int64
	SessionProviderConfig string
	SessionCookieLifeTime int
	SessionAutoSetCookie  bool
	SessionDomain         string
A
astaxie 已提交
88 89
}

A
astaxie 已提交
90 91 92 93
type LogConfig struct {
	AccessLogs  bool
	FileLineNum bool
	Output      map[string]string // Store Adaptor : config
A
astaxie 已提交
94 95
}

A
astaxie 已提交
96 97 98 99 100 101 102 103 104 105 106 107 108 109
var (
	// BConfig is the default config for Application
	BConfig *BeegoConfig
	// AppConfig is the instance of Config, store the config information from file
	AppConfig *beegoAppConfig
	// AppConfigPath is the path to the config files
	AppConfigPath string
	// AppConfigProvider is the provider for the config, default is ini
	AppConfigProvider = "ini"
	// TemplateCache stores template caching
	TemplateCache map[string]*template.Template
	// GlobalSessions is the instance for the session manager
	GlobalSessions *session.Manager
)
A
astaxie 已提交
110

A
astaxie 已提交
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
func init() {
	BConfig = &BeegoConfig{
		AppName:             "beego",
		RunMode:             "dev",
		RouterCaseSensitive: true,
		ServerName:          "beegoServer:" + VERSION,
		RecoverPanic:        true,
		CopyRequestBody:     false,
		EnableGzip:          false,
		MaxMemory:           1 << 26, //64MB
		EnableErrorsShow:    true,
		Listen: Listen{
			Graceful:      false,
			ServerTimeOut: 0,
			ListenTCP4:    false,
			HTTPEnable:    true,
			HTTPAddr:      "",
			HTTPPort:      8080,
			HTTPSEnable:   false,
			HTTPSAddr:     "",
			HTTPSPort:     10443,
			HTTPSCertFile: "",
			HTTPSKeyFile:  "",
			AdminEnable:   false,
			AdminAddr:     "",
			AdminPort:     8088,
			EnableFcgi:    false,
			EnableStdIo:   false,
		},
		WebConfig: WebConfig{
			AutoRender:             true,
			EnableDocs:             false,
			FlashName:              "BEEGO_FLASH",
			FlashSeperator:         "BEEGOFLASH",
			DirectoryIndex:         false,
			StaticDir:              map[string]string{"/static": "static"},
			StaticExtensionsToGzip: []string{".css", ".js"},
			TemplateLeft:           "{{",
			TemplateRight:          "}}",
			ViewsPath:              "views",
			EnableXSRF:             false,
			XSRFKEY:                "beegoxsrf",
			XSRFExpire:             0,
			Session: SessionConfig{
				SessionOn:             false,
				SessionProvider:       "memory",
				SessionName:           "beegosessionID",
				SessionGCMaxLifetime:  3600,
				SessionProviderConfig: "",
				SessionCookieLifeTime: 0, //set cookie default is the brower life
				SessionAutoSetCookie:  true,
				SessionDomain:         "",
			},
		},
		Log: LogConfig{
			AccessLogs:  false,
			FileLineNum: true,
			Output:      map[string]string{"console": ""},
		},
A
astaxie 已提交
170
	}
A
astaxie 已提交
171 172
}

A
astaxie 已提交
173 174 175 176 177 178
// ParseConfig parsed default config file.
// now only support ini, next will support json.
func ParseConfig() (err error) {
	if AppConfigPath == "" {
		if utils.FileExists(filepath.Join("conf", "app.conf")) {
			AppConfigPath = filepath.Join("conf", "app.conf")
179
		} else {
R
Ryan A. Chapman 已提交
180 181
			ac := config.NewFakeConfig()
			AppConfig = &beegoAppConfig{ac}
A
astaxie 已提交
182
			return
R
Ryan A. Chapman 已提交
183
		}
P
Pengfei Xue 已提交
184
	}
A
astaxie 已提交
185 186 187 188
	AppConfig, err = newAppConfig(AppConfigProvider, AppConfigPath)
	if err != nil {
		return err
	}
B
Bill Davis 已提交
189
	envRunMode := os.Getenv("BEEGO_RUNMODE")
A
astaxie 已提交
190
	// set the runmode first
B
Bill Davis 已提交
191
	if envRunMode != "" {
A
astaxie 已提交
192
		BConfig.RunMode = envRunMode
193
	} else if runmode := AppConfig.String("RunMode"); runmode != "" {
A
astaxie 已提交
194
		BConfig.RunMode = runmode
A
astaxie 已提交
195
	}
196

A
astaxie 已提交
197
	BConfig.Listen.HTTPAddr = AppConfig.String("HTTPAddr")
198

199
	if v, err := AppConfig.Int("HTTPPort"); err == nil {
A
astaxie 已提交
200
		BConfig.Listen.HTTPPort = v
A
astaxie 已提交
201
	}
A
astaxie 已提交
202

A
astaxie 已提交
203
	if v, err := AppConfig.Bool("ListenTCP4"); err == nil {
A
astaxie 已提交
204
		BConfig.Listen.ListenTCP4 = v
A
astaxie 已提交
205 206
	}

207
	if v, err := AppConfig.Bool("EnableHTTPListen"); err == nil {
A
astaxie 已提交
208
		BConfig.Listen.HTTPEnable = v
A
astaxie 已提交
209
	}
210

A
astaxie 已提交
211
	if maxmemory, err := AppConfig.Int64("MaxMemory"); err == nil {
A
astaxie 已提交
212
		BConfig.MaxMemory = maxmemory
A
astaxie 已提交
213
	}
214

A
astaxie 已提交
215
	if appname := AppConfig.String("AppName"); appname != "" {
A
astaxie 已提交
216
		BConfig.AppName = appname
A
astaxie 已提交
217
	}
218

A
astaxie 已提交
219
	if autorender, err := AppConfig.Bool("AutoRender"); err == nil {
A
astaxie 已提交
220
		BConfig.WebConfig.AutoRender = autorender
A
astaxie 已提交
221
	}
222

A
astaxie 已提交
223
	if autorecover, err := AppConfig.Bool("RecoverPanic"); err == nil {
A
astaxie 已提交
224
		BConfig.RecoverPanic = autorecover
A
astaxie 已提交
225
	}
226

A
astaxie 已提交
227
	if views := AppConfig.String("ViewsPath"); views != "" {
A
astaxie 已提交
228
		BConfig.WebConfig.ViewsPath = views
A
astaxie 已提交
229
	}
230

A
astaxie 已提交
231
	if sessionon, err := AppConfig.Bool("SessionOn"); err == nil {
A
astaxie 已提交
232
		BConfig.WebConfig.Session.SessionOn = sessionon
A
astaxie 已提交
233
	}
234

A
astaxie 已提交
235
	if sessProvider := AppConfig.String("SessionProvider"); sessProvider != "" {
A
astaxie 已提交
236
		BConfig.WebConfig.Session.SessionProvider = sessProvider
A
astaxie 已提交
237
	}
238

A
astaxie 已提交
239
	if sessName := AppConfig.String("SessionName"); sessName != "" {
A
astaxie 已提交
240
		BConfig.WebConfig.Session.SessionName = sessName
A
astaxie 已提交
241
	}
242

243
	if sessProvConfig := AppConfig.String("SessionProviderConfig"); sessProvConfig != "" {
A
astaxie 已提交
244
		BConfig.WebConfig.Session.SessionProviderConfig = sessProvConfig
A
astaxie 已提交
245
	}
246

A
astaxie 已提交
247
	if sessMaxLifeTime, err := AppConfig.Int64("SessionGCMaxLifetime"); err == nil && sessMaxLifeTime != 0 {
A
astaxie 已提交
248
		BConfig.WebConfig.Session.SessionGCMaxLifetime = sessMaxLifeTime
A
astaxie 已提交
249
	}
250

A
astaxie 已提交
251
	if sesscookielifetime, err := AppConfig.Int("SessionCookieLifeTime"); err == nil && sesscookielifetime != 0 {
A
astaxie 已提交
252
		BConfig.WebConfig.Session.SessionCookieLifeTime = sesscookielifetime
A
astaxie 已提交
253
	}
254

J
John Deng 已提交
255
	if enableFcgi, err := AppConfig.Bool("EnableFcgi"); err == nil {
A
astaxie 已提交
256
		BConfig.Listen.EnableFcgi = enableFcgi
A
astaxie 已提交
257
	}
258

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

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

267
	if timeout, err := AppConfig.Int64("HTTPServerTimeOut"); err == nil {
A
astaxie 已提交
268
		BConfig.Listen.ServerTimeOut = timeout
A
astaxie 已提交
269
	}
270

271
	if errorsshow, err := AppConfig.Bool("EnableErrorsShow"); err == nil {
A
astaxie 已提交
272
		BConfig.EnableErrorsShow = errorsshow
A
astaxie 已提交
273
	}
274

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

A
astaxie 已提交
279
	if xsrfkey := AppConfig.String("XSRFKEY"); xsrfkey != "" {
A
astaxie 已提交
280
		BConfig.WebConfig.XSRFKEY = xsrfkey
A
astaxie 已提交
281
	}
282

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

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

A
astaxie 已提交
291
	if tplleft := AppConfig.String("TemplateLeft"); tplleft != "" {
A
astaxie 已提交
292
		BConfig.WebConfig.TemplateLeft = tplleft
A
astaxie 已提交
293
	}
294

A
astaxie 已提交
295
	if tplright := AppConfig.String("TemplateRight"); tplright != "" {
A
astaxie 已提交
296
		BConfig.WebConfig.TemplateRight = tplright
A
astaxie 已提交
297
	}
298

299
	if httptls, err := AppConfig.Bool("EnableHTTPTLS"); err == nil {
A
astaxie 已提交
300
		BConfig.Listen.HTTPSEnable = httptls
A
astaxie 已提交
301
	}
A
astaxie 已提交
302

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

307
	if certfile := AppConfig.String("HTTPCertFile"); certfile != "" {
A
astaxie 已提交
308
		BConfig.Listen.HTTPSCertFile = certfile
A
astaxie 已提交
309
	}
310

311
	if keyfile := AppConfig.String("HTTPKeyFile"); keyfile != "" {
A
astaxie 已提交
312
		BConfig.Listen.HTTPSKeyFile = keyfile
A
astaxie 已提交
313
	}
314

A
astaxie 已提交
315
	if serverName := AppConfig.String("BeegoServerName"); serverName != "" {
A
astaxie 已提交
316
		BConfig.ServerName = serverName
A
astaxie 已提交
317
	}
318

A
astaxie 已提交
319
	if flashname := AppConfig.String("FlashName"); flashname != "" {
A
astaxie 已提交
320
		BConfig.WebConfig.FlashName = flashname
A
astaxie 已提交
321
	}
322

A
astaxie 已提交
323
	if flashseperator := AppConfig.String("FlashSeperator"); flashseperator != "" {
A
astaxie 已提交
324
		BConfig.WebConfig.FlashSeperator = flashseperator
A
astaxie 已提交
325
	}
326

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

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

A
astaxie 已提交
359
	if enableadmin, err := AppConfig.Bool("EnableAdmin"); err == nil {
A
astaxie 已提交
360
		BConfig.Listen.AdminEnable = enableadmin
A
astaxie 已提交
361
	}
362

363
	if adminhttpaddr := AppConfig.String("AdminHTTPAddr"); adminhttpaddr != "" {
A
astaxie 已提交
364
		BConfig.Listen.AdminAddr = adminhttpaddr
A
astaxie 已提交
365
	}
A
astaxie 已提交
366

367
	if adminhttpport, err := AppConfig.Int("AdminHTTPPort"); err == nil {
A
astaxie 已提交
368
		BConfig.Listen.AdminPort = adminhttpport
A
astaxie 已提交
369
	}
A
astaxie 已提交
370

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

A
astaxie 已提交
375
	if casesensitive, err := AppConfig.Bool("RouterCaseSensitive"); err == nil {
A
astaxie 已提交
376
		BConfig.RouterCaseSensitive = casesensitive
377
	}
378
	if graceful, err := AppConfig.Bool("Graceful"); err == nil {
A
astaxie 已提交
379
		BConfig.Listen.Graceful = graceful
380
	}
A
astaxie 已提交
381
	return nil
382
}
A
astaxie 已提交
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 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511

type beegoAppConfig struct {
	innerConfig config.Configer
}

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

func (b *beegoAppConfig) Set(key, val string) error {
	err := b.innerConfig.Set(BConfig.RunMode+"::"+key, val)
	if err == nil {
		return err
	}
	return b.innerConfig.Set(key, val)
}

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

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

func (b *beegoAppConfig) Int(key string) (int, error) {
	v, err := b.innerConfig.Int(BConfig.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(BConfig.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(BConfig.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(BConfig.RunMode + "::" + key)
	if err != nil {
		return b.innerConfig.Float(key)
	}
	return v, nil
}

func (b *beegoAppConfig) DefaultString(key string, defaultval string) string {
	v := b.String(key)
	if v != "" {
		return v
	}
	return defaultval
}

func (b *beegoAppConfig) DefaultStrings(key string, defaultval []string) []string {
	v := b.Strings(key)
	if len(v) != 0 {
		return v
	}
	return defaultval
}

func (b *beegoAppConfig) DefaultInt(key string, defaultval int) int {
	v, err := b.Int(key)
	if err == nil {
		return v
	}
	return defaultval
}

func (b *beegoAppConfig) DefaultInt64(key string, defaultval int64) int64 {
	v, err := b.Int64(key)
	if err == nil {
		return v
	}
	return defaultval
}

func (b *beegoAppConfig) DefaultBool(key string, defaultval bool) bool {
	v, err := b.Bool(key)
	if err == nil {
		return v
	}
	return defaultval
}

func (b *beegoAppConfig) DefaultFloat(key string, defaultval float64) float64 {
	v, err := b.Float(key)
	if err == nil {
		return v
	}
	return 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)
}