config.go 8.4 KB
Newer Older
1 2 3 4 5
package beego

import (
	"html/template"
	"os"
6
	"path/filepath"
7 8 9
	"runtime"
	"strconv"
	"strings"
P
Pengfei Xue 已提交
10 11

	"github.com/astaxie/beego/config"
12
	"github.com/astaxie/beego/logs"
P
Pengfei Xue 已提交
13
	"github.com/astaxie/beego/session"
14 15 16
)

var (
17
	// beego application
傅小黑 已提交
18
	BeeApp *App
19
	// application configurations
傅小黑 已提交
20 21 22 23
	AppName       string
	AppPath       string
	AppConfigPath string
	StaticDir     map[string]string
24
	// template caching map
傅小黑 已提交
25
	TemplateCache map[string]*template.Template
26 27 28
	// files with should be compressed with gzip (.js,.css,etc)
	StaticExtensionsToGzip []string
	// http server configurations
傅小黑 已提交
29 30 31 32 33
	HttpAddr     string
	HttpPort     int
	HttpTLS      bool
	HttpCertFile string
	HttpKeyFile  string
34
	// flag of auto recover panic
傅小黑 已提交
35
	RecoverPanic bool
36
	// flag of render template automatically
傅小黑 已提交
37 38
	AutoRender bool
	ViewsPath  string
39
	// run mode, "dev" or "prod"
傅小黑 已提交
40 41
	RunMode   string
	AppConfig config.ConfigContainer
42
	// global session mananger
傅小黑 已提交
43
	GlobalSessions *session.Manager
44
	// flag of starting session auto. default is false.
傅小黑 已提交
45
	SessionOn bool
46
	// default session provider, memory, mysql , redis ,etc.
傅小黑 已提交
47
	SessionProvider string
48
	// the cookie name when saving session id into cookie.
傅小黑 已提交
49
	SessionName string
50
	// session gc time for auto cleaning expired session.
傅小黑 已提交
51
	SessionGCMaxLifetime int64
52
	// if use mysql/redis/file provider, define save path to connection info.
傅小黑 已提交
53
	SessionSavePath string
54
	// session hash generation func.
傅小黑 已提交
55
	SessionHashFunc string
56
	// session hash salt string.
傅小黑 已提交
57
	SessionHashKey string
58
	// the life time of session id in cookie.
59 60 61
	SessionCookieLifeTime int
	UseFcgi               bool
	MaxMemory             int64
62
	// flag of enable gzip
傅小黑 已提交
63
	EnableGzip bool
64
	// flag of display directory index. default is false.
傅小黑 已提交
65
	DirectoryIndex bool
66
	// flag of hot update checking in app self. default is false.
傅小黑 已提交
67 68
	EnableHotUpdate   bool
	HttpServerTimeOut int64
69
	// flag of show errors in page. if true, show error and trace info in page rendered with error template.
傅小黑 已提交
70
	ErrorsShow bool
71
	// xsrf hash salt string.
傅小黑 已提交
72
	XSRFKEY string
73
	// flag of enable xsrf.
傅小黑 已提交
74
	EnableXSRF bool
75
	// the expiry of xsrf value.
傅小黑 已提交
76
	XSRFExpire int
77
	// flag of copy raw request body in context.
傅小黑 已提交
78 79 80
	CopyRequestBody bool
	TemplateLeft    string
	TemplateRight   string
81
	// beego server name exported in response header.
傅小黑 已提交
82
	BeegoServerName string
83
	// flag of enable admin module to log every request info.
傅小黑 已提交
84
	EnableAdmin bool
85
	// http server configurations for admin module.
傅小黑 已提交
86 87
	AdminHttpAddr string
	AdminHttpPort int
88 89
)

A
astaxie 已提交
90
func init() {
91
	// create beego application
A
astaxie 已提交
92
	BeeApp = NewApp()
P
Pengfei Xue 已提交
93 94

	// initialize default configurations
95 96
	AppPath, _ = filepath.Abs(filepath.Dir(os.Args[0]))
	os.Chdir(AppPath)
P
Pengfei Xue 已提交
97

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

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

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

	// set this to 0.0.0.0 to make this app available to externally
A
astaxie 已提交
106
	HttpAddr = ""
107
	HttpPort = 8080
P
Pengfei Xue 已提交
108

109
	AppName = "beego"
P
Pengfei Xue 已提交
110

111
	RunMode = "dev" //default runmod
P
Pengfei Xue 已提交
112

113
	AutoRender = true
P
Pengfei Xue 已提交
114

115
	RecoverPanic = true
P
Pengfei Xue 已提交
116

117
	ViewsPath = "views"
P
Pengfei Xue 已提交
118

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

128
	UseFcgi = false
P
Pengfei Xue 已提交
129

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

132
	EnableGzip = false
P
Pengfei Xue 已提交
133

134
	AppConfigPath = filepath.Join(AppPath, "conf", "app.conf")
P
Pengfei Xue 已提交
135

136
	HttpServerTimeOut = 0
P
Pengfei Xue 已提交
137

138
	ErrorsShow = true
P
Pengfei Xue 已提交
139

140 141
	XSRFKEY = "beegoxsrf"
	XSRFExpire = 0
P
Pengfei Xue 已提交
142

143 144
	TemplateLeft = "{{"
	TemplateRight = "}}"
P
Pengfei Xue 已提交
145

146
	BeegoServerName = "beegoServer"
P
Pengfei Xue 已提交
147

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

152
	runtime.GOMAXPROCS(runtime.NumCPU())
P
Pengfei Xue 已提交
153

154 155 156 157
	// init BeeLogger
	BeeLogger = logs.NewLogger(10000)
	BeeLogger.SetLogger("console", "")

P
Pengfei Xue 已提交
158 159
	err := ParseConfig()
	if err != nil && !os.IsNotExist(err) {
160 161
		// for init if doesn't have app.conf will not panic
		Info(err)
P
Pengfei Xue 已提交
162
	}
163 164
}

165 166
// ParseConfig parsed default config file.
// now only support ini, next will support json.
167 168 169 170 171
func ParseConfig() (err error) {
	AppConfig, err = config.NewConfig("ini", AppConfigPath)
	if err != nil {
		return err
	} else {
172
		HttpAddr = AppConfig.String("HttpAddr")
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 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

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

		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 hotupdate, err := AppConfig.Bool("HotUpdate"); err == nil {
			EnableHotUpdate = hotupdate
		}

		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
		}

		if httptls, err := AppConfig.Bool("HttpTLS"); err == nil {
			HttpTLS = httptls
		}

287
		if certfile := AppConfig.String("HttpCertFile"); certfile != "" {
288 289 290 291 292 293 294 295 296 297 298 299 300 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
		}

		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["/"+url2fsmap[0]] = url2fsmap[1]
				} else {
					StaticDir["/"+url2fsmap[0]] = url2fsmap[0]
				}
			}
		}
312

F
Francois 已提交
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
		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)
				}
			}
		}
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343

		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
}