Skip to content

Commit 2602505

Browse files
committed
feat: use dsn rather than db url
1 parent d6c0d57 commit 2602505

File tree

2 files changed

+23
-3
lines changed

2 files changed

+23
-3
lines changed

internal/database/client.go

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ package database
77

88
import (
99
"database/sql"
10+
"fmt"
1011
"io/ioutil"
1112
"log"
1213
"path/filepath"
@@ -15,15 +16,28 @@ import (
1516
_ "github.com/jackc/pgx/v4/stdlib"
1617
)
1718

19+
type DSN struct {
20+
Host string
21+
Port int
22+
User string
23+
Password string
24+
DBName string
25+
}
26+
27+
func (dsn DSN) ToString() string {
28+
return fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",
29+
dsn.Host, dsn.Port, dsn.User, dsn.Password, dsn.DBName)
30+
}
31+
1832
// Client store the database path.
1933
type Client struct {
2034
sqlPath string
2135
db *sql.DB
2236
}
2337

2438
// NewClient exactly create a new instance of Client.
25-
func NewClient(dbURL string, sqlPath string) Client {
26-
db, err := sql.Open("pgx", dbURL)
39+
func NewClient(dsn DSN, sqlPath string) Client {
40+
db, err := sql.Open("pgx", dsn.ToString())
2741
if err != nil {
2842
log.Fatal(err)
2943
}

main.go

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,13 @@ type errorBody struct {
2121
}
2222

2323
func main() {
24-
dbClient := database.NewClient(os.Getenv("database_url"), "db/sql")
24+
dbClient := database.NewClient(database.DSN{
25+
Host: "database",
26+
Port: 5432,
27+
User: os.Getenv("POSTGRES_USER"),
28+
Password: os.Getenv("POSTGRES_PASSWORD"),
29+
DBName: os.Getenv("POSTGRES_DB"),
30+
}, "db/sql")
2531
err := dbClient.InitDB()
2632
if err != nil {
2733
log.Fatal(err)

0 commit comments

Comments
 (0)