我正在尝试用 go 语言创建 API,但出现错误。如何解决?我将发布错误文本。错误:无法初始化数据库,收到错误拨号 tcp:0:connectex:请求的地址在其上下文中无效failed to initialize database, got error dial tcp :0: connectex: The requested address is not valid in its context.panic: DB Error: dial tcp :0: connectex: The requested address is not valid in its context.goroutine 1 [running]:ToDoList-Server/model.DBConnection() C:/Users/81804/enviroment/todo/ToDoList-Server/model/db.go:21 +0x225main.main() C:/Users/81804/enviroment/todo/ToDoList-Server/main.go:10 +0x2apackage modelimport ( "database/sql" "fmt" "os" _ "github.com/go-sql-driver/mysql" "gorm.io/driver/mysql" "gorm.io/gorm")var db *gorm.DB// DB接続とテーブルを作成するfunc DBConnection() *sql.DB { dsn := GetDBConfig() var err error db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{}) if err != nil { panic(fmt.Errorf("DB Error: %w", err)) } CreateTable(db) sqlDB, err := db.DB() if err != nil { panic(fmt.Errorf("DB Error: %w", err)) } return sqlDB}// DBのdsnを取得するfunc GetDBConfig() string { user := os.Getenv("DB_USERNAME") password := os.Getenv("DB_PASSWORD") hostname := os.Getenv("DB_HOSTNAME") port := os.Getenv("DB_PORT") dbname := os.Getenv("DB_DBNAME") dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s", user, password, hostname, port, dbname) + "?charset=utf8mb4&parseTime=True&loc=Local" return dsn}// Task型のテーブルを作成するfunc CreateTable(db *gorm.DB) { db.AutoMigrate(&Task{})}
- 1 回答
- 0 关注
- 583 浏览
添加回答
举报
0/150
提交
取消