// 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 }
// NewRedisStoreWithDB - like NewRedisStore but accepts `DB` parameter to select // redis DB instead of using the default one ("0") func NewRediStoreWithDB(size int, network string, address, password, DB string, keyPairs []byte) *redisStore { store, _ := redistore.NewRediStoreWithDB(size, network, address, password, DB, keyPairs) return &redisStore{store} }