packages/database/db/option.go
2025-06-17 14:02:19 +08:00

46 lines
948 B
Go

package db
import (
"context"
"fmt"
)
type config struct {
ctx context.Context
mysql *string
pg *string
sqlite *string
}
type OptionFn func(*config)
func WithCtx(ctx context.Context) OptionFn {
return func(c *config) {
if ctx != nil {
c.ctx = ctx
}
}
}
func WithMysql(host string, port int, user string, password string, database string) OptionFn {
return func(c *config) {
dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", user, password, host, port, database)
c.mysql = &dsn
}
}
func WithPg(host string, port int, user string, password string, database string) OptionFn {
return func(c *config) {
dsn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%d sslmode=disable TimeZone=Asia/Shanghai", host, user, password, database, port)
c.pg = &dsn
}
}
func WithSqlite(path string) OptionFn {
return func(c *config) {
if path != "" {
c.sqlite = &path
}
}
}