Add database driver and config module
Signed-off-by: Asai Neko <sugar@sne.moe>
This commit is contained in:
24
data/drivers/postgres.go
Normal file
24
data/drivers/postgres.go
Normal file
@@ -0,0 +1,24 @@
|
||||
package drivers
|
||||
|
||||
import (
|
||||
"nixcn-cms/config"
|
||||
"strings"
|
||||
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func SplitHostPort(url string) (host, port string) {
|
||||
if !strings.Contains(url, ":") {
|
||||
return url, "5432"
|
||||
}
|
||||
split := strings.Split(url, ":")
|
||||
return split[0], split[1]
|
||||
}
|
||||
|
||||
func Postgres(dsn ExternalDSN) (*DBClient, error) {
|
||||
host, port := SplitHostPort(dsn.Host)
|
||||
conn := "host=" + host + " user=" + dsn.Username + " password=" + dsn.Password + " dbname=" + dsn.Name + " port=" + port + " sslmode=disable TimeZone=" + config.TZ()
|
||||
db, err := gorm.Open(postgres.Open(conn), &gorm.Config{})
|
||||
return &DBClient{db}, err
|
||||
}
|
||||
16
data/drivers/types.go
Normal file
16
data/drivers/types.go
Normal file
@@ -0,0 +1,16 @@
|
||||
package drivers
|
||||
|
||||
import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type ExternalDSN struct {
|
||||
Host string
|
||||
Name string
|
||||
Username string
|
||||
Password string
|
||||
}
|
||||
|
||||
type DBClient struct {
|
||||
*gorm.DB
|
||||
}
|
||||
Reference in New Issue
Block a user