Skip to content

Commit 5c4a473

Browse files
committed
Using config.toml with database configuration params
1 parent bbdbb95 commit 5c4a473

File tree

3 files changed

+44
-13
lines changed

3 files changed

+44
-13
lines changed

db.go

+6-11
Original file line numberDiff line numberDiff line change
@@ -6,18 +6,13 @@ import (
66
_ "github.com/lib/pq"
77
)
88

9-
const (
10-
DB_USER = "user"
11-
DB_PASSWORD = "password"
12-
DB_NAME = "dbname"
13-
DB_HOST = "127.0.0.1"
14-
DB_PORT = "5432"
15-
DB_SSLMODE = "disable"
16-
)
17-
189
func GetDbConnection() (*sql.DB, error) {
19-
dbinfo := fmt.Sprintf("postgres://%s:%s@%s:%s/%s?sslmode=%s",
20-
DB_USER, DB_PASSWORD, DB_HOST, DB_PORT, DB_NAME, DB_SSLMODE)
10+
config, err := ParseDbConfig(".")
11+
if err != nil {
12+
return nil, err
13+
}
14+
dbinfo := fmt.Sprintf("postgres://%s:%s@%s:%v/%s?sslmode=%s",
15+
config.User, config.Password, config.Host, config.Port, config.Database, config.SslMode)
2116
db, err := sql.Open("postgres", dbinfo)
2217
if err != nil {
2318
return nil, err

parser.go

+37
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@ package main
22

33
import (
44
"bytes"
5+
"errors"
56
"fmt"
7+
"github.com/BurntSushi/toml"
68
"github.com/xeipuuv/gojsonschema"
79
"io/ioutil"
810
"strings"
@@ -92,3 +94,38 @@ func ParseSqlTemplate(path string, route *Route) error {
9294
route.SqlTemplate = tmpl
9395
return nil
9496
}
97+
98+
type DbConfig struct {
99+
User string
100+
Password string
101+
Database string
102+
Host string
103+
Port int
104+
SslMode string
105+
}
106+
107+
func ParseDbConfig(path string) (*DbConfig, error) {
108+
conf := &DbConfig{}
109+
content, err := ioutil.ReadFile(path + "/config.toml")
110+
if err != nil {
111+
return nil, errors.New(fmt.Sprintf("Error while reading config.toml configuration: %v", err))
112+
}
113+
_, err = toml.Decode(string(content), &conf)
114+
if err != nil {
115+
return nil, err
116+
}
117+
if conf.User == "" {
118+
conf.User = "postgres"
119+
}
120+
if conf.Host == "" {
121+
conf.Host = "127.0.0.1"
122+
}
123+
if conf.Port == 0 {
124+
conf.Port = 5432
125+
}
126+
if conf.SslMode == "" {
127+
conf.SslMode = "disable"
128+
}
129+
return conf, nil
130+
131+
}

testapp/config.toml

+1-2
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
1-
[database]
21
user = "user"
32
password = "password"
43
database = "dbname"
54
host = "127.0.0.1"
6-
port = "5434"
5+
port = 5434
76
sslmode = "disable"

0 commit comments

Comments
 (0)