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

7 8 9
package beego

import (
A
astaxie 已提交
10
	"fmt"
11 12
	"html/template"
	"os"
13
	"path/filepath"
14 15 16
	"runtime"
	"strconv"
	"strings"
P
Pengfei Xue 已提交
17 18

	"github.com/astaxie/beego/config"
19
	"github.com/astaxie/beego/logs"
P
Pengfei Xue 已提交
20
	"github.com/astaxie/beego/session"
21
	"github.com/astaxie/beego/utils"
22 23 24
)

var (
傅小黑 已提交
25 26 27
	BeeApp                 *App // beego application
	AppName                string
	AppPath                string
28
	workPath               string
傅小黑 已提交
29 30 31 32
	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 已提交
33
	EnableHttpListen       bool
傅小黑 已提交
34 35
	HttpAddr               string
	HttpPort               int
A
astaxie 已提交
36 37
	EnableHttpTLS          bool
	HttpsPort              int
傅小黑 已提交
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
	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 已提交
54
	SessionAutoSetCookie   bool             // auto setcookie
傅小黑 已提交
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
	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
71 72
	FlashName              string // name of the flash variable found in response header and cookie
	FlashSeperator         string // used to seperate flash key:value
A
astaxie 已提交
73
	AppConfigProvider      string // config provider
74 75
)

A
astaxie 已提交
76
func init() {
77
	// create beego application
A
astaxie 已提交
78
	BeeApp = NewApp()
P
Pengfei Xue 已提交
79

80 81
	workPath, _ = os.Getwd()
	workPath, _ = filepath.Abs(workPath)
P
Pengfei Xue 已提交
82
	// initialize default configurations
83
	AppPath, _ = filepath.Abs(filepath.Dir(os.Args[0]))
84 85 86 87 88 89 90 91 92 93

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

A
astaxie 已提交
95 96
	AppConfigProvider = "ini"

97
	StaticDir = make(map[string]string)
P
Pengfei Xue 已提交
98
	StaticDir["/static"] = "static"
99

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

A
typo  
astaxie 已提交
102
	TemplateCache = make(map[string]*template.Template)
P
Pengfei Xue 已提交
103 104

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

A
astaxie 已提交
107
	HttpAddr = ""
108
	HttpPort = 8080
P
Pengfei Xue 已提交
109

A
astaxie 已提交
110
	HttpsPort = 10443
A
astaxie 已提交
111

112
	AppName = "beego"
P
Pengfei Xue 已提交
113

114
	RunMode = "dev" //default runmod
P
Pengfei Xue 已提交
115

116
	AutoRender = true
P
Pengfei Xue 已提交
117

118
	RecoverPanic = true
P
Pengfei Xue 已提交
119

120
	ViewsPath = "views"
P
Pengfei Xue 已提交
121

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

132
	UseFcgi = false
P
Pengfei Xue 已提交
133

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

136
	EnableGzip = false
P
Pengfei Xue 已提交
137

138
	HttpServerTimeOut = 0
P
Pengfei Xue 已提交
139

140
	ErrorsShow = true
P
Pengfei Xue 已提交
141

142 143
	XSRFKEY = "beegoxsrf"
	XSRFExpire = 0
P
Pengfei Xue 已提交
144

145 146
	TemplateLeft = "{{"
	TemplateRight = "}}"
P
Pengfei Xue 已提交
147

A
astaxie 已提交
148
	BeegoServerName = "beegoServer:" + VERSION
P
Pengfei Xue 已提交
149

150
	EnableAdmin = false
P
Pengfei Xue 已提交
151
	AdminHttpAddr = "127.0.0.1"
152
	AdminHttpPort = 8088
P
Pengfei Xue 已提交
153

154 155 156
	FlashName = "BEEGO_FLASH"
	FlashSeperator = "BEEGOFLASH"

157
	runtime.GOMAXPROCS(runtime.NumCPU())
P
Pengfei Xue 已提交
158

159 160
	// init BeeLogger
	BeeLogger = logs.NewLogger(10000)
A
astaxie 已提交
161 162 163 164
	err := BeeLogger.SetLogger("console", "")
	if err != nil {
		fmt.Println("init console log error:", err)
	}
165

A
astaxie 已提交
166
	err = ParseConfig()
P
Pengfei Xue 已提交
167
	if err != nil && !os.IsNotExist(err) {
168 169
		// for init if doesn't have app.conf will not panic
		Info(err)
P
Pengfei Xue 已提交
170
	}
171 172
}

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

		if v, err := AppConfig.Int("HttpPort"); err == nil {
			HttpPort = v
		}

A
astaxie 已提交
187 188 189 190
		if v, err := AppConfig.Bool("EnableHttpListen"); err == nil {
			EnableHttpListen = v
		}

191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
		if maxmemory, err := AppConfig.Int64("MaxMemory"); err == nil {
			MaxMemory = maxmemory
		}

		if appname := AppConfig.String("AppName"); appname != "" {
			AppName = appname
		}

		if runmode := AppConfig.String("RunMode"); runmode != "" {
			RunMode = runmode
		}

		if autorender, err := AppConfig.Bool("AutoRender"); err == nil {
			AutoRender = autorender
		}

		if autorecover, err := AppConfig.Bool("RecoverPanic"); err == nil {
			RecoverPanic = autorecover
		}

		if views := AppConfig.String("ViewsPath"); views != "" {
			ViewsPath = views
		}

		if sessionon, err := AppConfig.Bool("SessionOn"); err == nil {
			SessionOn = sessionon
		}

		if sessProvider := AppConfig.String("SessionProvider"); sessProvider != "" {
			SessionProvider = sessProvider
		}

		if sessName := AppConfig.String("SessionName"); sessName != "" {
			SessionName = sessName
		}

		if sesssavepath := AppConfig.String("SessionSavePath"); sesssavepath != "" {
			SessionSavePath = sesssavepath
		}

		if sesshashfunc := AppConfig.String("SessionHashFunc"); sesshashfunc != "" {
			SessionHashFunc = sesshashfunc
		}

		if sesshashkey := AppConfig.String("SessionHashKey"); sesshashkey != "" {
			SessionHashKey = sesshashkey
		}

		if sessMaxLifeTime, err := AppConfig.Int("SessionGCMaxLifetime"); err == nil && sessMaxLifeTime != 0 {
			int64val, _ := strconv.ParseInt(strconv.Itoa(sessMaxLifeTime), 10, 64)
			SessionGCMaxLifetime = int64val
		}

		if sesscookielifetime, err := AppConfig.Int("SessionCookieLifeTime"); err == nil && sesscookielifetime != 0 {
			SessionCookieLifeTime = sesscookielifetime
		}

		if usefcgi, err := AppConfig.Bool("UseFcgi"); err == nil {
			UseFcgi = usefcgi
		}

		if enablegzip, err := AppConfig.Bool("EnableGzip"); err == nil {
			EnableGzip = enablegzip
		}

		if directoryindex, err := AppConfig.Bool("DirectoryIndex"); err == nil {
			DirectoryIndex = directoryindex
		}

		if timeout, err := AppConfig.Int64("HttpServerTimeOut"); err == nil {
			HttpServerTimeOut = timeout
		}

		if errorsshow, err := AppConfig.Bool("ErrorsShow"); err == nil {
			ErrorsShow = errorsshow
		}

		if copyrequestbody, err := AppConfig.Bool("CopyRequestBody"); err == nil {
			CopyRequestBody = copyrequestbody
		}

		if xsrfkey := AppConfig.String("XSRFKEY"); xsrfkey != "" {
			XSRFKEY = xsrfkey
		}

		if enablexsrf, err := AppConfig.Bool("EnableXSRF"); err == nil {
			EnableXSRF = enablexsrf
		}

		if expire, err := AppConfig.Int("XSRFExpire"); err == nil {
			XSRFExpire = expire
		}

		if tplleft := AppConfig.String("TemplateLeft"); tplleft != "" {
			TemplateLeft = tplleft
		}

		if tplright := AppConfig.String("TemplateRight"); tplright != "" {
			TemplateRight = tplright
		}

A
astaxie 已提交
292 293 294 295 296 297
		if httptls, err := AppConfig.Bool("EnableHttpTLS"); err == nil {
			EnableHttpTLS = httptls
		}

		if httpsport, err := AppConfig.Int("HttpsPort"); err == nil {
			HttpsPort = httpsport
298 299
		}

300
		if certfile := AppConfig.String("HttpCertFile"); certfile != "" {
301 302 303 304 305 306 307 308 309 310 311
			HttpCertFile = certfile
		}

		if keyfile := AppConfig.String("HttpKeyFile"); keyfile != "" {
			HttpKeyFile = keyfile
		}

		if serverName := AppConfig.String("BeegoServerName"); serverName != "" {
			BeegoServerName = serverName
		}

312 313 314 315 316 317 318 319
		if flashname := AppConfig.String("FlashName"); flashname != "" {
			FlashName = flashname
		}

		if flashseperator := AppConfig.String("FlashSeperator"); flashseperator != "" {
			FlashSeperator = flashseperator
		}

320 321 322 323 324 325 326
		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 {
A
astaxie 已提交
327
					StaticDir["/"+strings.TrimRight(url2fsmap[0], "/")] = url2fsmap[1]
328
				} else {
A
astaxie 已提交
329
					StaticDir["/"+strings.TrimRight(url2fsmap[0], "/")] = url2fsmap[0]
330 331 332
				}
			}
		}
333

F
Francois 已提交
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
		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
					}
					extWithDot := ext
					if extWithDot[:1] != "." {
						extWithDot = "." + extWithDot
					}
					StaticExtensionsToGzip = append(StaticExtensionsToGzip, extWithDot)
				}
			}
		}
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364

		if enableadmin, err := AppConfig.Bool("EnableAdmin"); err == nil {
			EnableAdmin = enableadmin
		}

		if adminhttpaddr := AppConfig.String("AdminHttpAddr"); adminhttpaddr != "" {
			AdminHttpAddr = adminhttpaddr
		}

		if adminhttpport, err := AppConfig.Int("AdminHttpPort"); err == nil {
			AdminHttpPort = adminhttpport
		}
	}
	return nil
}