u
This commit is contained in:
1 parent
4ef00e1d5d
commit
9e00adf2fe
27 files changed
+1104
No files matched your search
@@ -0,0 +1,38 @@
|
||||
package bootstrap
|
||||
|
||||
import (
|
||||
"allapp-go-v2/internal/config"
|
||||
"allapp-go-v2/internal/pkg/logger"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type App struct {
|
||||
Config *config.Config
|
||||
Db *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewApp() (*App, error) {
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 初始化日志
|
||||
if err := logger.Init(cfg.App.Env); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
InitUniqueId(cfg)
|
||||
|
||||
db, err := InitDB(cfg)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &App{
|
||||
Config: cfg,
|
||||
Db: db,
|
||||
}, nil
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package bootstrap
|
||||
|
||||
import (
|
||||
"allapp-go-v2/internal/config"
|
||||
"allapp-go-v2/internal/pkg/uniqueid"
|
||||
)
|
||||
|
||||
func InitUniqueId(cfg *config.Config) {
|
||||
options := uniqueid.NewIdGeneratorOptions(cfg.UniqueID.WorkerID)
|
||||
uniqueid.SetIdGenerator(options)
|
||||
}
|
||||
Reference in new issue
Block a user