Golang变量避坑
var DB *gorm.DB
func SetupDb() {
mysqlUrl := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?allowNativePasswords=true&charset=utf8mb4&parseTime=true&loc=Local",
config.Conf.Mysql.User,
config.Conf.Mysql.Password,
config.Conf.Mysql.Host,
config.Conf.Mysql.Port,
config.Conf.Mysql.Name)
DB, err := gorm.Open("mysql", mysqlUrl) // 此处的 DB是局部变量,全局变量不受影响
if err != nil {
log.Fatalln(err)
}
DB.LogMode(true)
createTable(&APP{})
createTable(&Env{})
DB.AutoMigrate(&APP{}, &Env{})
}
func createTable(t interface{}) {
if !DB.HasTable(t) { // 此处调用会产生空指针错误
DB.CreateTable(t)
}
}Last updated