Add database driver and config module

Signed-off-by: Asai Neko <sugar@sne.moe>
This commit is contained in:
2025-12-19 17:38:51 +08:00
parent e2345a8d4a
commit dc128c0392
11 changed files with 196 additions and 7 deletions

24
data/drivers/postgres.go Normal file
View 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
View 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
}