package db import ( "fmt" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/mysql" _ "github.com/jinzhu/gorm/dialects/postgres" "github.com/joho/godotenv" "golang.org/x/crypto/bcrypt" "log" "os" "wqyblog_api_go/models" ) var DB *gorm.DB func Init() { err := godotenv.Load() if err != nil { log.Println("Not found .env file. Only use system variables.") } dbType := os.Getenv("DB_TYPE") dbUser := os.Getenv("DB_USER") dbPassword := os.Getenv("DB_PASSWORD") dbName := os.Getenv("DB_NAME") dbHost := os.Getenv("DB_HOST") dbPort := os.Getenv("DB_PORT") var dbUri string switch dbType { case "mysql": dbUri = fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local", dbUser, dbPassword, dbHost, dbPort, dbName) case "postgresql": dbUri = fmt.Sprintf("host=%s port=%s user=%s dbname=%s sslmode=disable password=%s", dbHost, dbPort, dbUser, dbName, dbPassword) default: log.Fatalf("Unsupported DB_TYPE: %s", dbType) } DB, err = gorm.Open(dbType, dbUri) if err != nil { log.Fatalf("Failed to connect to database: %v", err) } DB.AutoMigrate(&models.Post{}) DB.AutoMigrate(&models.User{}) log.Println("Database connected") // 如果没有ADMIN用户 if DB.First(&models.User{}, "username = ?", "admin").RecordNotFound() { log.Println("No ADMIN user found, creating one...") // 添加ADMIN用户 密码使用 bcrypt 123456@321 password, err := bcrypt.GenerateFromPassword([]byte("123456@321"), bcrypt.DefaultCost) if err != nil { log.Fatalf("Failed to generate password: %v", err) } DB.Create(&models.User{ Username: "admin", Password: password, }) } else { log.Println("ADMIN user found, skipping creation...") } }