Esempio n. 1
0
// LoadConfig creates a config object by specified config file.
func (cfg *PolarisConfig) LoadConfig() bool {
	cfgFile, err := goconfig.LoadConfigFile(cfg.CfgFile)
	if err != nil {
		log.Error("Failed to load config file:", cfg.CfgFile, ":", err)
		return false
	}

	cfg.DirStatic = cfgFile.MustValue("system", "dir_public", "public")
	cfg.DirTemplate = cfgFile.MustValue("system", "dir_template", "view")
	cfg.DirLog = cfgFile.MustValue("system", "dir_log", ".")
	cfg.TempExtension = cfgFile.MustValue("system", "tpl_extension", ".tpl")
	cfg.TempEncoding = cfgFile.MustValue("system", "tpl_encoding", "UTF-8")
	cfg.SessionStore = cfgFile.MustValue("session", "session_store", "redis")
	cfg.SessionName = cfgFile.MustValue("session", "session_name", "my_session")
	cfg.SessionMask = cfgFile.MustValue("session", "session_mask", "")
	cfg.url = map[string]string{
		"RedirectUrl":   cfgFile.MustValue("system", "RedirectUrl", "/new-login"),
		"RedirectParam": cfgFile.MustValue("system", "RedirectParam", "new-next"),
	}
	cfg.Port = cfgFile.MustInt("system", "port", 3000)

	cfg.Redis = &RedisConfig{
		Size:     cfgFile.MustInt("redis", "redis_maxidel", 10),
		Network:  cfgFile.MustValue("redis", "redis_network", "tcp"),
		Address:  cfgFile.MustValue("redis", "redis_address", "localhost:6379"),
		Password: cfgFile.MustValue("redis", "redis_password", ""),
		DB:       cfgFile.MustValue("redis", "redis_DB", "0"),
	}

	cfg.Database = DBConfig{
		Type:     cfgFile.MustValue("database", "db_type", "mssql"),
		Driver:   "",
		Host:     cfgFile.MustValue("database", "db_server", "localhost"),
		Port:     cfgFile.MustValue("database", "db_port", "1433"),
		Database: cfgFile.MustValue("database", "db_database", "temdb"),
		User:     cfgFile.MustValue("database", "db_user", "sa"),
		Password: cfgFile.MustValue("database", "db_password", ""),
		Verbose:  cfgFile.MustBool("database", "db_verbose", true),
		LogFile:  cfgFile.MustValue("database", "db_log", ""),
	}
	cfg.DBType = cfg.Database.Driver
	cfg.CfgHandle = cfgFile

	// Add file log
	if len(cfg.DirLog) > 0 {
		year, month, day := time.Now().Date()
		cfg.LogFile = cfg.DirLog + "/" + fmt.Sprintf("app_%04d%02d%02d.log", year, month, day)

		cfg.LogHandle, _ = os.OpenFile(cfg.LogFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
		if cfg.LogHandle != nil {
			log.AddLogger("file", cfg.LogHandle, log.ALL)
		}
	}

	return true
}
Esempio n. 2
0
func (egn *DBEngine) Close() bool {
	if egn != nil {
		err := egn.Db.Close()
		if err != nil {
			log.Error("Failed to close DB connecttion : " + err.Error())
			return false
		}
		return true
	}
	return true
}
Esempio n. 3
0
// InitDB initialize a connection to specified database
func (conf *DBConfig) InitDB() *DBEngine {
	// get driver
	dialect, driver := dialectAndDriver(conf.Type)
	conf.Driver = driver

	strDSN := conf.String()
	if strDSN == "" {
		log.Error("Invalid DSN has been provided : " + strDSN)
		return nil
	}
	// log.Debug("[" + driver + "] ==> " + strDSN)
	// open connection
	db, err := sql.Open(driver, strDSN)
	if err != nil {
		log.Error("Error connecting to db: " + err.Error())
		return nil
	}
	// fmt.Printf("db = %#v\n", db)
	// dbEngine := &gorp.DbMap{Db: db, Dialect: dialect}
	dbEngine := &DBEngine{DbMap: gorp.DbMap{Db: db, Dialect: dialect}}
	// open SQL log or not
	if conf.Verbose {
		if len(conf.LogFile) > 0 {
			sql_log, err := os.OpenFile(conf.LogFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
			if err == nil {
				dbEngine.TraceOn("[SQL]", stdlog.New(sql_log, "sql", stdlog.Lmicroseconds))
			} else {
				dbEngine.TraceOn("[SQL]", log.GetLogger("file"))
			}
		} else {
			dbEngine.TraceOn("[SQL]", log.GetLogger("file"))
		}
	} else {
		dbEngine.TraceOff()
	}

	conf._ready = true
	return dbEngine
}
Esempio n. 4
0
func (app *PolarisApplication) RotateLog() bool {
	config := app.Config.GetBasicConfig()

	// get new log
	year, month, day := time.Now().Date()
	new_log := config.DirLog + "/" + fmt.Sprintf("app_%04d%02d%02d.log", year, month, day)
	new_handle, err := os.OpenFile(new_log, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
	if err != nil {
		log.Error("error opening file: %v", err)
		return false
	}

	// replace it
	if config.LogHandle != nil {
		config.LogHandle.Close()
	}
	config.LogHandle = new_handle
	config.LogFile = new_log
	return true
}
Esempio n. 5
0
// NewApp creates a application object with some basic default middleware. It's based on ClassicMartini.
// Classic also maps martini.Routes as a service.
func NewApp(cfg Config, newUser func() sessionauth.User) *PolarisApplication {
	// Create config object
	if !cfg.LoadConfig() {
		log.Error("Failed to init config object")
		return nil
	}
	config := cfg.GetBasicConfig()

	log.Debug("Application started......")
	// create router object
	rtr := martini.NewRouter()

	// create matini object
	server := martini.New()

	// replace log for testing
	server.Map((*log.LevelBasedLogger)(nil))
	server.Use(Logger())

	server.Use(martini.Recovery())
	server.Use(martini.Static(config.DirStatic))
	server.MapTo(rtr, (*martini.Routes)(nil))
	server.Action(rtr.Handle)

	app := &PolarisApplication{server, rtr, cfg, nil, nil}

	log.Debug("Add middleware -- martini-contrib/render......")
	app.Use(render.Renderer(render.Options{
		Directory:  config.DirTemplate,
		Extensions: []string{config.TempExtension},
		Charset:    config.TempEncoding,
	}))

	log.Debug("Add middleware -- martini-contrib/sessions......")
	if "redis" == strings.ToLower(strings.TrimSpace(config.SessionStore)) {
		var err error
		log.Debug("Connect to redis......" + config.Redis.Address)
		if app.Store == nil {
			app.Store, err = redistore.NewRediStoreWithDB(
				config.Redis.Size,
				config.Redis.Network,
				config.Redis.Address,
				config.Redis.Password,
				config.Redis.DB,
				[]byte(config.SessionMask),
			)
			if err != nil {
				log.Error("Failed to connect to redis : " + err.Error())
				return nil
			}
		}
		app.Use(sessions.Sessions(config.SessionName, app.Store))
	} else {
		app.Use(sessions.Sessions(config.SessionName, sessions.NewCookieStore([]byte(config.SessionMask))))
	}

	if len(config.Database.Database) > 0 {
		log.Debug("Connect to databse......[" + config.Database.Database + "]")
		// ensure the connection can be made corrrectly, connect to the dabase when starting
		app.DbEngine = config.Database.InitDB()
		if app.DbEngine == nil {
			log.Error("Failed to connect to database (" + config.Database.Database + ")")
			return nil
		}
		log.Debug("Add middleware -- gorp......")
		app.Use(config.Database.MartiniHandler())
	}

	log.Debug("Add middleware -- martini-contrib/sessionauth......")
	app.Use(sessionauth.SessionUser(newUser))
	sessionauth.RedirectUrl = config.url["RedirectUrl"]
	sessionauth.RedirectParam = config.url["RedirectParam"]

	log.Debug("Add User defined router mapping......")
	if !cfg.RoterMap(app) {
		log.Error("Failed to add Roter Mapping")
		return nil
	}
	return app
}