Files
folium/dbx/init.go
Snowykami b0d224dc64 feat: add logging and collector implementations
- Introduced `hertzx` package with `NewHertz` function for server initialization.
- Implemented `logx` package with various log collectors: Console, Loki, Elasticsearch, and Prometheus.
- Added `Logger` struct to manage logging levels and collectors.
- Created environment variable loading functionality in `osx` package to support configuration.
- Enhanced logging capabilities with structured log entries and asynchronous collection.
2025-11-01 13:20:02 +08:00

89 lines
2.1 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package dbx
import (
"git.liteyuki.org/LiteyukiStudio/folium/osx"
"gorm.io/gorm"
)
type DBDriverType string
const (
Postgres DBDriverType = "postgres"
MySQL DBDriverType = "mysql"
SQLite DBDriverType = "sqlite"
)
// DBConfig 持有数据库连接配置,可以部分填写,未填写的字段会从环境变量读取默认值
type DBConfig struct {
Driver DBDriverType
Host string
Port string
User string
Password string
Sslmode string
}
// NewDBConfigFromEnv 从环境变量构造默认配置
func NewDBConfigFromEnv() *DBConfig {
return &DBConfig{
Driver: DBDriverType(osx.GetEnv("DB_DRIVER", string(Postgres))),
Host: osx.GetEnv("DB_HOST", "localhost"),
Port: osx.GetEnv("DB_PORT", "5432"),
User: osx.GetEnv("DB_USER", "user"),
Password: osx.GetEnv("DB_PASSWORD", "password"),
Sslmode: osx.GetEnv("DB_SSLMODE", "disable"),
}
}
// FillDefaultsFromEnv 对于为空的字段,用环境变量或默认值补全
func (c *DBConfig) FillDefaultsFromEnv() {
if c == nil {
c = &DBConfig{}
}
if c.Driver == "" {
c.Driver = DBDriverType(osx.GetEnv("DB_DRIVER", string(Postgres)))
}
if c.Host == "" {
c.Host = osx.GetEnv("DB_HOST", "localhost")
}
if c.Port == "" {
c.Port = osx.GetEnv("DB_PORT", "5432")
}
if c.User == "" {
c.User = osx.GetEnv("DB_USER", "user")
}
if c.Password == "" {
c.Password = osx.GetEnv("DB_PASSWORD", "password")
}
if c.Sslmode == "" {
c.Sslmode = osx.GetEnv("DB_SSLMODE", "disable")
}
}
// GetDB 使用给定配置(或 DefaultDBConfig if nil并返回对应的 *gorm.DB
// 如果 dbName 为空则使用配置中的 Name 字段(仍会从环境变量补全)
func GetDB(cfg *DBConfig, dbName string) *gorm.DB {
if cfg == nil {
cfg = NewDBConfigFromEnv()
}
cfg.FillDefaultsFromEnv()
if dbName == "" {
dbName = osx.GetEnv("DB_NAME", "database")
if dbName == "" {
panic("database name is not specified")
}
}
switch cfg.Driver {
case Postgres:
return GetPostgresDB(cfg, dbName)
case MySQL:
return GetMySQLDB(cfg, dbName)
case SQLite:
return GetSQLiteDB(cfg, dbName)
default:
panic("unsupported database driver: " + string(cfg.Driver))
}
}