// NewApplication is the constructor for Application struct. // // If testing is true, connects to the "test" database. func NewApplication(testing bool) (*Application, error) { u, err := libunix.CurrentUser() if err != nil { return nil, err } dbname := "forty-thieves" if testing { dbname += "-test" } dsn := libenv.EnvWithDefault( "DSN", fmt.Sprintf("postgres://%v@localhost:5432/%s?sslmode=disable", u, dbname)) db, err := sqlx.Connect("postgres", dsn) if err != nil { return nil, err } cookieStoreSecret := libenv.EnvWithDefault("COOKIE_SECRET", "ittwiP92o0oi6P4i") app := &Application{} app.dsn = dsn app.db = db app.cookieStore = sessions.NewCookieStore([]byte(cookieStoreSecret)) return app, err }
func newDbForTest(t *testing.T) *sqlx.DB { var err error pguser, _, pghost, pgport, pgsslmode := os.Getenv("PGUSER"), os.Getenv("PGPASSWORD"), os.Getenv("PGHOST"), os.Getenv("PGPORT"), os.Getenv("PGSSLMODE") if pguser == "" { pguser, err = libunix.CurrentUser() if err != nil { t.Fatalf("Getting current user should never fail. Error: %v", err) } } if pghost == "" { pghost = "localhost" } if pgport == "" { pgport = "5432" } if pgsslmode == "" { pgsslmode = "disable" } db, err := sqlx.Connect("postgres", fmt.Sprintf("postgres://%v@%v:%v/forty-thieves-test?sslmode=%v", pguser, pghost, pgport, pgsslmode)) if err != nil { t.Fatalf("Connecting to local postgres should never fail. Error: %v", err) } return db }