database/database.go (view raw)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
package database import ( "fmt" "k3yst0n3/models" "log" "os" "gorm.io/driver/postgres" "gorm.io/gorm" "gorm.io/gorm/logger" ) type Dbinstance struct { Db *gorm.DB } var DB Dbinstance func ConnectDb() { dsn := fmt.Sprintf( "host=postgres user=%s password=%s dbname=%s port=5432 sslmode=disable TimeZone=Asia/Shanghai", "test", "test", "test", // os.Getenv("DB_USER"), // os.Getenv("DB_PASSWORD"), // os.Getenv("DB_NAME"), ) db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{ Logger: logger.Default.LogMode(logger.Info), }) if err != nil { log.Fatal("Failed to connect to database. \n", err) os.Exit(2) } log.Println("connected") db.Logger = logger.Default.LogMode(logger.Info) log.Println("running migrations") db.AutoMigrate(&models.Fact{}) DB = Dbinstance{ Db: db, } } |