Skip to content

Commit

Permalink
create postgres connection
Browse files Browse the repository at this point in the history
  • Loading branch information
Hiroshi Kurabayashi committed Jan 21, 2020
1 parent ddb18f8 commit 233604e
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 3 deletions.
15 changes: 12 additions & 3 deletions config/config.go
Expand Up @@ -18,6 +18,15 @@ type config struct {
DBNAME string
OPTION string
}
Postgres struct {
DBMS string
USER string
PASS string
HOST string
PORT string
DBNAME string
OPTION string
}
}

var C config
Expand All @@ -31,9 +40,9 @@ func LoadConfig() {
viper.AutomaticEnv()

if err := viper.ReadInConfig(); err != nil {
fmt.Println("load config error")
fmt.Println(err)
os.Exit(1)
fmt.Println("load config error")
fmt.Println(err)
os.Exit(1)
}

if err := viper.Unmarshal(&Conf); err != nil {
Expand Down
8 changes: 8 additions & 0 deletions config/config.yml
Expand Up @@ -6,3 +6,11 @@ mysql:
port: "3306"
dbname: "goSample"
option: "?charset=utf8&parseTime=True&loc=Local"
postgres:
dbms: "postgres"
user: "user"
pass: "secret"
host: "0.0.0.0"
port: "5432"
dbname: "goSample"
option: "sslmode=disable"
31 changes: 31 additions & 0 deletions infrastructure/datastore/dbPostgreSQL.go
@@ -0,0 +1,31 @@
package datastore

import (
"fmt"

"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"

"api/config"
)

func NewPostgreSQL() *gorm.DB {
connectString := fmt.Sprintf(
"host=%s port=%s user=%s dbname= %s password=%s %s",
config.C.Postgres.HOST,
config.C.Postgres.PORT,
config.C.Postgres.USER,
config.C.Postgres.DBNAME,
config.C.Postgres.PASS,
config.C.Postgres.OPTION,
)
db, err := gorm.Open(config.C.Postgres.DBMS, connectString)

if err != nil {
panic(err.Error())
}

db.LogMode(true)

return db
}

0 comments on commit 233604e

Please sign in to comment.