u
This commit is contained in:
1 parent
4ef00e1d5d
commit
9e00adf2fe
27 files changed
+1104
No files matched your search
@@ -0,0 +1,53 @@
|
||||
package bootstrap
|
||||
|
||||
import (
|
||||
"allapp-go-v2/internal/config"
|
||||
"allapp-go-v2/internal/pkg/logger"
|
||||
"context"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
func InitDB(cfg *config.Config) (*pgxpool.Pool, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
pg := cfg.Postgres
|
||||
|
||||
// ssl mode
|
||||
sslMode := "disable"
|
||||
if pg.SslMode {
|
||||
sslMode = "require"
|
||||
}
|
||||
|
||||
// 转义密码(防止特殊字符问题)
|
||||
password := url.QueryEscape(pg.Password)
|
||||
|
||||
// 构建 DSN
|
||||
dsn := fmt.Sprintf(
|
||||
"postgres://%s:%s@%s:%d/%s?sslmode=%s&timezone=%s",
|
||||
pg.User,
|
||||
password,
|
||||
pg.Host,
|
||||
pg.Port,
|
||||
pg.Dbname,
|
||||
sslMode,
|
||||
pg.TimeZone,
|
||||
)
|
||||
|
||||
db, err := pgxpool.New(ctx, dsn)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := db.Ping(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
logger.Log.Info("√ 数据库连接成功")
|
||||
|
||||
return db, nil
|
||||
}
|
||||
Reference in new issue
Block a user