Search code examples
gogo-gorm

error: failed to initialize database, got error dial tcp :0: connectex: The requested address is not valid in its context


I am trying to create an API in go language, but I get an error. How can this be resolved? I will post the error text. error: failed to initialize database, got error dial tcp :0: connectex: The requested address is not valid in its context

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{})
}

Solution

  • try to format your dsn string as follows:

    dsn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s post=%s", hostname, user, password, dbname, port)