changeset 28:714787accd26

Fetch database connection string parts from configuration.
author Sascha L. Teichmann <sascha.teichmann@intevation.de>
date Mon, 25 Jun 2018 15:34:32 +0200
parents c3e2cd7fa46f
children a9d3990b083b
files auth/opendb.go config/config.go
diffstat 2 files changed, 45 insertions(+), 1 deletions(-) [+]
line wrap: on
line diff
--- a/auth/opendb.go	Mon Jun 25 13:26:48 2018 +0200
+++ b/auth/opendb.go	Mon Jun 25 15:34:32 2018 +0200
@@ -3,10 +3,34 @@
 import (
 	"database/sql"
 	"errors"
+	"fmt"
+	"strings"
+
+	"gemma.intevation.de/gemma/config"
+
+	_ "github.com/jackc/pgx/stdlib"
 )
 
 var ErrNotImplementedYet = errors.New("Not implemented, yet!")
 
+const driver = "pgx"
+
+// dbQuote quotes strings to be able to contain whitespace
+// and backslashes in database DSN strings.
+var dbQuote = strings.NewReplacer(`\`, `\\`, `'`, `\'`).Replace
+
+// dbDSN creates a data source name suitable for sql.Open on
+// PostgreSQL databases.
+func dbDSN(host string, port uint, dbname, user, password string, sslmode string) string {
+	return fmt.Sprintf("host='%s' port=%d dbname='%s' user='%s' password='%s' sslmode='%s'",
+		dbQuote(host), port, dbQuote(dbname),
+		dbQuote(user), dbQuote(password), sslmode)
+}
+
 func opendb(user, password string) (*sql.DB, error) {
-	return nil, ErrNotImplementedYet
+	return sql.Open(driver, dbDSN(
+		config.Config.DBHost, config.Config.DBPort,
+		config.Config.DBName,
+		user, password,
+		config.Config.DBSSLMode))
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/config/config.go	Mon Jun 25 15:34:32 2018 +0200
@@ -0,0 +1,20 @@
+package config
+
+var Config = NewConfiguration()
+
+type Configuration struct {
+	DBHost    string
+	DBPort    uint
+	DBName    string
+	DBSSLMode string
+}
+
+func NewConfiguration() *Configuration {
+	// TODO: Load from file.
+	return &Configuration{
+		DBHost:    "localhost",
+		DBPort:    5432,
+		DBName:    "gemma",
+		DBSSLMode: "require",
+	}
+}