feat: 新增项目公共工具包,包含日志、错误、数据库、缓存、公共proto
This commit is contained in:
32
backend/shared/postgres/postgres.go
Normal file
32
backend/shared/postgres/postgres.go
Normal file
@@ -0,0 +1,32 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"shared/logger"
|
||||
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Host string
|
||||
Port string
|
||||
User string
|
||||
Password string
|
||||
DBName string
|
||||
SSLMode string
|
||||
}
|
||||
|
||||
func NewPostgresDB(cfg Config) (*gorm.DB, error) {
|
||||
dsn := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=%s",
|
||||
cfg.Host, cfg.Port, cfg.User, cfg.Password, cfg.DBName, cfg.SSLMode)
|
||||
|
||||
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
|
||||
if err != nil {
|
||||
logger.Error().Err(err).Msg("Failed to connect to PostgreSQL database")
|
||||
return nil, err
|
||||
}
|
||||
|
||||
logger.Info().Msg("Connected to PostgreSQL database successfully")
|
||||
return db, nil
|
||||
}
|
||||
Reference in New Issue
Block a user