Skip to content

Commit

Permalink
update: Cloud SQL との接続を確立するため、DBとの接続方法を変更
Browse files Browse the repository at this point in the history
  • Loading branch information
YKhm20020 committed Nov 14, 2024
1 parent 95af6be commit d7199cb
Showing 1 changed file with 18 additions and 11 deletions.
29 changes: 18 additions & 11 deletions app/infrastructure/setup_db.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,12 @@ import (
)

var (
host string
user string
password string
dbname string
port string
host string
user string
password string
dbname string
port string
unixSocketPath string
)

func SetupDB() *sql.DB {
Expand All @@ -22,10 +23,13 @@ func SetupDB() *sql.DB {
panic("完了変数の取得に失敗")
}

dsn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%s sslmode=disable",
host, user, password, dbname, port)
// dsn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%s sslmode=disable",
// host, user, password, dbname, port)

db, err := sql.Open("postgres", dsn)
dbURI := fmt.Sprintf("%s:%s@unix(%s)/%s?parseTime=true",
user, password, unixSocketPath, dbname)

db, err := sql.Open("postgres", dbURI)
if err != nil {
panic("データベース接続失敗")
} else {
Expand All @@ -36,16 +40,19 @@ func SetupDB() *sql.DB {
}

func loadEnv() error {
err := godotenv.Load(".env")
if err != nil {
return err
if product := os.Getenv(("PRODUCTION")); product == "" {
err := godotenv.Load(".env")
if err != nil {
fmt.Println("fail to load .env file")
}
}

host = os.Getenv("DB_HOST")
user = os.Getenv("DB_USER")
password = os.Getenv("DB_PASSWORD")
dbname = os.Getenv("DB_NAME")
port = os.Getenv("DB_PORT")
unixSocketPath = os.Getenv("INSTANCE_UNIX_SOCKET")

return nil
}

0 comments on commit d7199cb

Please sign in to comment.