错误:初始化数据库失败,拨号 tcp 出错:0:connectex:请求的地址在其上下文中无效
我正在尝试用 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 +0x225
main.main()
C:/Users/81804/enviroment/todo/ToDoList-Server/main.go:10 +0x2a
package model
import (
"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{})
}