config.go 12.8 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 {
F
fuxiaohei 已提交
180
			AppConfig = &beegoAppConfig{config.NewFakeConfig()}
A
astaxie 已提交
181
			return
R
Ryan A. Chapman 已提交
182
		}
P
Pengfei Xue 已提交
183
	}
A
astaxie 已提交
184 185 186 187
	AppConfig, err = newAppConfig(AppConfigProvider, AppConfigPath)
	if err != nil {
		return err
	}
A
astaxie 已提交
188
	// set the runmode first
F
fuxiaohei 已提交
189
	if envRunMode := os.Getenv("BEEGO_RUNMODE"); envRunMode != "" {
A
astaxie 已提交
190
		BConfig.RunMode = envRunMode
191
	} else if runmode := AppConfig.String("RunMode"); runmode != "" {
A
astaxie 已提交
192
		BConfig.RunMode = runmode
A
astaxie 已提交
193
	}
194

A
astaxie 已提交
195 196 197 198 199 200 201 202 203
	BConfig.AppName = AppConfig.DefaultString("AppName", BConfig.AppName)
	BConfig.RecoverPanic = AppConfig.DefaultBool("RecoverPanic", BConfig.RecoverPanic)
	BConfig.RouterCaseSensitive = AppConfig.DefaultBool("RouterCaseSensitive", BConfig.RouterCaseSensitive)
	BConfig.ServerName = AppConfig.DefaultString("BeegoServerName", BConfig.ServerName)
	BConfig.EnableGzip = AppConfig.DefaultBool("EnableGzip", BConfig.EnableGzip)
	BConfig.EnableErrorsShow = AppConfig.DefaultBool("EnableErrorsShow", BConfig.EnableErrorsShow)
	BConfig.CopyRequestBody = AppConfig.DefaultBool("CopyRequestBody", BConfig.CopyRequestBody)
	BConfig.MaxMemory = AppConfig.DefaultInt64("MaxMemory", BConfig.MaxMemory)
	BConfig.Listen.Graceful = AppConfig.DefaultBool("Graceful", BConfig.Listen.Graceful)
A
astaxie 已提交
204
	BConfig.Listen.HTTPAddr = AppConfig.String("HTTPAddr")
A
astaxie 已提交
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
	BConfig.Listen.HTTPPort = AppConfig.DefaultInt("HTTPPort", BConfig.Listen.HTTPPort)
	BConfig.Listen.ListenTCP4 = AppConfig.DefaultBool("ListenTCP4", BConfig.Listen.ListenTCP4)
	BConfig.Listen.HTTPEnable = AppConfig.DefaultBool("EnableHTTPListen", BConfig.Listen.HTTPEnable)
	BConfig.Listen.HTTPSEnable = AppConfig.DefaultBool("EnableHTTPTLS", BConfig.Listen.HTTPSEnable)
	BConfig.Listen.HTTPSPort = AppConfig.DefaultInt("HTTPSPort", BConfig.Listen.HTTPSPort)
	BConfig.Listen.HTTPSCertFile = AppConfig.DefaultString("HTTPCertFile", BConfig.Listen.HTTPSCertFile)
	BConfig.Listen.HTTPSKeyFile = AppConfig.DefaultString("HTTPKeyFile", BConfig.Listen.HTTPSKeyFile)
	BConfig.Listen.AdminEnable = AppConfig.DefaultBool("EnableAdmin", BConfig.Listen.AdminEnable)
	BConfig.Listen.AdminAddr = AppConfig.DefaultString("AdminHTTPAddr", BConfig.Listen.AdminAddr)
	BConfig.Listen.AdminPort = AppConfig.DefaultInt("AdminHTTPPort", BConfig.Listen.AdminPort)
	BConfig.Listen.EnableFcgi = AppConfig.DefaultBool("EnableFcgi", BConfig.Listen.EnableFcgi)
	BConfig.Listen.ServerTimeOut = AppConfig.DefaultInt64("HTTPServerTimeOut", BConfig.Listen.ServerTimeOut)
	BConfig.WebConfig.AutoRender = AppConfig.DefaultBool("AutoRender", BConfig.WebConfig.AutoRender)
	BConfig.WebConfig.ViewsPath = AppConfig.DefaultString("ViewsPath", BConfig.WebConfig.ViewsPath)
	BConfig.WebConfig.DirectoryIndex = AppConfig.DefaultBool("DirectoryIndex", BConfig.WebConfig.DirectoryIndex)
A
astaxie 已提交
220 221 222
	BConfig.WebConfig.FlashName = AppConfig.DefaultString("FlashName", BConfig.WebConfig.FlashName)
	BConfig.WebConfig.FlashSeperator = AppConfig.DefaultString("FlashSeperator", BConfig.WebConfig.FlashSeperator)
	BConfig.WebConfig.EnableDocs = AppConfig.DefaultBool("EnableDocs", BConfig.WebConfig.EnableDocs)
A
astaxie 已提交
223 224 225 226 227 228 229 230 231 232 233 234
	BConfig.WebConfig.XSRFKEY = AppConfig.DefaultString("XSRFKEY", BConfig.WebConfig.XSRFKEY)
	BConfig.WebConfig.EnableXSRF = AppConfig.DefaultBool("EnableXSRF", BConfig.WebConfig.EnableXSRF)
	BConfig.WebConfig.XSRFExpire = AppConfig.DefaultInt("XSRFExpire", BConfig.WebConfig.XSRFExpire)
	BConfig.WebConfig.TemplateLeft = AppConfig.DefaultString("TemplateLeft", BConfig.WebConfig.TemplateLeft)
	BConfig.WebConfig.TemplateRight = AppConfig.DefaultString("TemplateRight", BConfig.WebConfig.TemplateRight)
	BConfig.WebConfig.Session.SessionOn = AppConfig.DefaultBool("SessionOn", BConfig.WebConfig.Session.SessionOn)
	BConfig.WebConfig.Session.SessionProvider = AppConfig.DefaultString("SessionProvider", BConfig.WebConfig.Session.SessionProvider)
	BConfig.WebConfig.Session.SessionName = AppConfig.DefaultString("SessionName", BConfig.WebConfig.Session.SessionName)
	BConfig.WebConfig.Session.SessionProviderConfig = AppConfig.DefaultString("SessionProviderConfig", BConfig.WebConfig.Session.SessionProviderConfig)
	BConfig.WebConfig.Session.SessionGCMaxLifetime = AppConfig.DefaultInt64("SessionGCMaxLifetime", BConfig.WebConfig.Session.SessionGCMaxLifetime)
	BConfig.WebConfig.Session.SessionCookieLifeTime = AppConfig.DefaultInt("SessionCookieLifeTime", BConfig.WebConfig.Session.SessionCookieLifeTime)

A
astaxie 已提交
235
	if sd := AppConfig.String("StaticDir"); sd != "" {
A
astaxie 已提交
236 237
		for k := range BConfig.WebConfig.StaticDir {
			delete(BConfig.WebConfig.StaticDir, k)
A
astaxie 已提交
238 239 240 241
		}
		sds := strings.Fields(sd)
		for _, v := range sds {
			if url2fsmap := strings.SplitN(v, ":", 2); len(url2fsmap) == 2 {
A
astaxie 已提交
242
				BConfig.WebConfig.StaticDir["/"+strings.TrimRight(url2fsmap[0], "/")] = url2fsmap[1]
A
astaxie 已提交
243
			} else {
A
astaxie 已提交
244
				BConfig.WebConfig.StaticDir["/"+strings.TrimRight(url2fsmap[0], "/")] = url2fsmap[0]
245 246
			}
		}
A
astaxie 已提交
247
	}
248

A
astaxie 已提交
249 250
	if sgz := AppConfig.String("StaticExtensionsToGzip"); sgz != "" {
		extensions := strings.Split(sgz, ",")
J
JessonChan 已提交
251
		fileExts := []string{}
J
JessonChan 已提交
252 253 254 255
		for _, ext := range extensions {
			ext = strings.TrimSpace(ext)
			if ext == "" {
				continue
F
Francois 已提交
256
			}
J
JessonChan 已提交
257 258 259
			if !strings.HasPrefix(ext, ".") {
				ext = "." + ext
			}
J
JessonChan 已提交
260 261 262
			fileExts = append(fileExts, ext)
		}
		if len(fileExts) > 0 {
A
astaxie 已提交
263
			BConfig.WebConfig.StaticExtensionsToGzip = fileExts
F
Francois 已提交
264
		}
A
astaxie 已提交
265 266
	}
	return nil
267
}
A
astaxie 已提交
268 269 270 271 272 273 274 275 276 277

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
	}
F
fuxiaohei 已提交
278
	return &beegoAppConfig{ac}, nil
A
astaxie 已提交
279 280 281
}

func (b *beegoAppConfig) Set(key, val string) error {
F
fuxiaohei 已提交
282
	if err := b.innerConfig.Set(BConfig.RunMode+"::"+key, val); err != nil {
A
astaxie 已提交
283 284 285 286 287 288
		return err
	}
	return b.innerConfig.Set(key, val)
}

func (b *beegoAppConfig) String(key string) string {
F
fuxiaohei 已提交
289 290
	if v := b.innerConfig.String(BConfig.RunMode + "::" + key); v != "" {
		return v
A
astaxie 已提交
291
	}
F
fuxiaohei 已提交
292
	return b.innerConfig.String(key)
A
astaxie 已提交
293 294 295
}

func (b *beegoAppConfig) Strings(key string) []string {
F
fuxiaohei 已提交
296 297
	if v := b.innerConfig.Strings(BConfig.RunMode + "::" + key); v[0] != "" {
		return v[0]
A
astaxie 已提交
298
	}
F
fuxiaohei 已提交
299
	return b.innerConfig.Strings(key)
A
astaxie 已提交
300 301 302
}

func (b *beegoAppConfig) Int(key string) (int, error) {
F
fuxiaohei 已提交
303 304
	if v, err := b.innerConfig.Int(BConfig.RunMode + "::" + key); err == nil {
		return v, nil
A
astaxie 已提交
305
	}
F
fuxiaohei 已提交
306
	return b.innerConfig.Int(key)
A
astaxie 已提交
307 308 309
}

func (b *beegoAppConfig) Int64(key string) (int64, error) {
F
fuxiaohei 已提交
310 311
	if v, err := b.innerConfig.Int64(BConfig.RunMode + "::" + key); err == nil {
		return v, nil
A
astaxie 已提交
312
	}
F
fuxiaohei 已提交
313
	return b.innerConfig.Int64(key)
A
astaxie 已提交
314 315 316
}

func (b *beegoAppConfig) Bool(key string) (bool, error) {
F
fuxiaohei 已提交
317 318
	if v, err := b.innerConfig.Bool(BConfig.RunMode + "::" + key); err == nil {
		return v, nil
A
astaxie 已提交
319
	}
F
fuxiaohei 已提交
320
	return b.innerConfig.Bool(key)
A
astaxie 已提交
321 322 323
}

func (b *beegoAppConfig) Float(key string) (float64, error) {
F
fuxiaohei 已提交
324 325
	if v, err := b.innerConfig.Float(BConfig.RunMode + "::" + key); err == nil {
		return v, nil
A
astaxie 已提交
326
	}
F
fuxiaohei 已提交
327
	return b.innerConfig.Float(key)
A
astaxie 已提交
328 329 330
}

func (b *beegoAppConfig) DefaultString(key string, defaultval string) string {
F
fuxiaohei 已提交
331
	if v := b.String(key); v != "" {
A
astaxie 已提交
332 333 334 335 336 337
		return v
	}
	return defaultval
}

func (b *beegoAppConfig) DefaultStrings(key string, defaultval []string) []string {
F
fuxiaohei 已提交
338
	if v := b.Strings(key); len(v) != 0 {
A
astaxie 已提交
339 340 341 342 343 344
		return v
	}
	return defaultval
}

func (b *beegoAppConfig) DefaultInt(key string, defaultval int) int {
F
fuxiaohei 已提交
345
	if v, err := b.Int(key); err == nil {
A
astaxie 已提交
346 347 348 349 350 351
		return v
	}
	return defaultval
}

func (b *beegoAppConfig) DefaultInt64(key string, defaultval int64) int64 {
F
fuxiaohei 已提交
352
	if v, err := b.Int64(key); err == nil {
A
astaxie 已提交
353 354 355 356 357 358
		return v
	}
	return defaultval
}

func (b *beegoAppConfig) DefaultBool(key string, defaultval bool) bool {
F
fuxiaohei 已提交
359
	if v, err := b.Bool(key); err == nil {
A
astaxie 已提交
360 361 362 363 364 365
		return v
	}
	return defaultval
}

func (b *beegoAppConfig) DefaultFloat(key string, defaultval float64) float64 {
F
fuxiaohei 已提交
366
	if v, err := b.Float(key); err == nil {
A
astaxie 已提交
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
		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)
}