57 lines
940 B
Go
57 lines
940 B
Go
![]() |
package storage
|
||
|
|
||
|
import (
|
||
|
"fmt"
|
||
|
"sync"
|
||
|
|
||
|
"gorm.io/driver/postgres"
|
||
|
"gorm.io/gorm"
|
||
|
)
|
||
|
|
||
|
type Storager interface{}
|
||
|
|
||
|
type storage struct {
|
||
|
db *gorm.DB
|
||
|
mux sync.RWMutex
|
||
|
}
|
||
|
|
||
|
type DBConfig struct {
|
||
|
Username string
|
||
|
Password string
|
||
|
Host string
|
||
|
Port int
|
||
|
Name string
|
||
|
}
|
||
|
|
||
|
func ProductionDataBase(conf *DBConfig) (*gorm.DB, error) {
|
||
|
// create dsn string
|
||
|
dsn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%d sslmode=disable TimeZone=Europe/Madrid",
|
||
|
conf.Host,
|
||
|
conf.Username,
|
||
|
conf.Password,
|
||
|
conf.Name,
|
||
|
conf.Port,
|
||
|
)
|
||
|
// create open database connection
|
||
|
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
|
||
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
return db, nil
|
||
|
}
|
||
|
|
||
|
func New(conf *DBConfig) (Storager, error) {
|
||
|
// database holder
|
||
|
var db *gorm.DB
|
||
|
// producctio
|
||
|
db, err := ProductionDataBase(conf)
|
||
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
// done
|
||
|
return &storage{
|
||
|
db: db,
|
||
|
mux: sync.RWMutex{},
|
||
|
}, nil
|
||
|
}
|