From 76a3b9b10550d333c0050b9410933146251218f6 Mon Sep 17 00:00:00 2001 From: Victor Lacasse-Beaudoin Date: Sat, 16 Sep 2023 16:28:18 -0400 Subject: [PATCH] Ajouter type dbclient.DBClient et func dbclient.New --- dbclient/dbclient.go | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/dbclient/dbclient.go b/dbclient/dbclient.go index 61c4d69..85049ea 100644 --- a/dbclient/dbclient.go +++ b/dbclient/dbclient.go @@ -1,2 +1,40 @@ // Package dbclient provides the database client used by the API server package dbclient + +import ( + "fmt" + + "github.com/jmoiron/sqlx" +) + +// DBClient holds a *sqlx.DB and implements methods to manipulate the database +type DBClient struct { + DB *sqlx.DB +} + +func New(host, database, user, password string, port int, useSSL bool) (*DBClient, error) { + var SSLMode string + + switch useSSL { + case true: + SSLMode = "enable" + case false: + SSLMode = "disable" + } + + connectionString := fmt.Sprintf("postgres://%s:%s@%s:%d/%s?sslmode=%s", + user, + password, + host, + port, + database, + SSLMode, + ) + + db, err := sqlx.Connect("pgx", connectionString) + if err != nil { + return nil, err + } + + return &DBClient{DB: db}, nil +}