This commit is contained in:
oneao committed 2025-10-31 17:28:45 +08:00
1 parent 200f72eb86
commit 91ae4cb474
19 files changed
+650 -148

No files matched your search

@@ -0,0 +1,59 @@
package config
import (
"base-go-v2/internal/types"
"github.com/spf13/viper"
"time"
)
// App 全局唯一导出配置实例,初始化默认值
var App = &types.AppConfig{
Server: types.AppConfig{}.Server,
JWT: types.AppConfig{}.JWT,
Db: types.AppConfig{}.Db,
Snowflake: types.AppConfig{}.Snowflake,
}
// 给部分字段设置默认值
func init() {
App.Server.Port = 8080
App.JWT.Secret = "default_secret"
App.JWT.Expiry = time.Hour
// 数据库只给连接池默认值
App.Db.MaxOpenConns = 10
App.Db.MaxIdleConns = 5
App.Db.ConnMaxLifetime = 30 * time.Minute
App.Snowflake.DatacenterID = 1
App.Snowflake.WorkerID = 1
}
// InitApplicationConfig 初始化配置
func InitApplicationConfig(configPath string) error {
v := viper.New()
v.SetConfigFile(configPath)
v.SetConfigType("yaml")
if err := v.ReadInConfig(); err != nil {
return err
}
if err := v.UnmarshalKey("server", &App.Server); err != nil {
return err
}
if err := v.UnmarshalKey("jwt", &App.JWT); err != nil {
return err
}
if err := v.UnmarshalKey("snowflake", &App.Snowflake); err != nil {
return err
}
if err := v.UnmarshalKey("db", &App.Db); err != nil {
return err
}
return nil
}
@@ -0,0 +1,62 @@
package database
import (
"base-go-v2/internal/config"
"database/sql"
"fmt"
"time"
_ "github.com/lib/pq"
)
var DB *sql.DB
var defaultPoolConfig = struct {
MaxOpenConns int
MaxIdleConns int
ConnMaxLifetime time.Duration
}{
MaxOpenConns: 10,
MaxIdleConns: 5,
ConnMaxLifetime: 30 * time.Minute,
}
func InitDb() error {
d := config.Db
// 构造 DSN
dsn := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",
d.Host, d.Port, d.User, d.Password, d.Dbname)
db, err := sql.Open("postgres", dsn)
if err != nil {
return fmt.Errorf("打开数据库失败: %w", err)
}
// 设置连接池(使用默认值,如果用户没传)
maxOpenConns := d.MaxOpenConns
if maxOpenConns == 0 {
maxOpenConns = defaultPoolConfig.MaxOpenConns
}
db.SetMaxOpenConns(maxOpenConns)
maxIdleConns := d.MaxIdleConns
if maxIdleConns == 0 {
maxIdleConns = defaultPoolConfig.MaxIdleConns
}
db.SetMaxIdleConns(maxIdleConns)
connMaxLifetime := d.ConnMaxLifetime
if connMaxLifetime == 0 {
connMaxLifetime = defaultPoolConfig.ConnMaxLifetime
}
db.SetConnMaxLifetime(connMaxLifetime)
// 测试连接
if err := db.Ping(); err != nil {
return fmt.Errorf("数据库连接测试失败: %w", err)
}
DB = db
return nil
}
@@ -0,0 +1,28 @@
package types
import "time"
// AppConfig 统一配置结构体
type AppConfig struct {
Server struct {
Port int
}
JWT struct {
Secret string
Expiry time.Duration
}
Db struct {
Host string
Port int
User string
Password string
Dbname string
MaxOpenConns int
MaxIdleConns int
ConnMaxLifetime time.Duration
}
Snowflake struct {
DatacenterID uint64
WorkerID uint64
}
}
@@ -0,0 +1,75 @@
package jwt
import (
"base-go-v2/internal/config"
"errors"
"github.com/golang-jwt/jwt/v5"
"time"
)
var (
ErrTokenExpired = errors.New("token expired")
ErrTokenInvalid = errors.New("token invalid")
)
// CustomClaims 定义自己的 payload 结构
type CustomClaims struct {
UserID string `json:"user_id"`
jwt.RegisteredClaims
}
// CreateToken 创建一个 JWT token
// 支持 config.App.JWT.Expiry == -1 永不过期
func CreateToken(orgID, userID string) (string, error) {
claims := CustomClaims{
UserID: userID,
RegisteredClaims: jwt.RegisteredClaims{
IssuedAt: jwt.NewNumericDate(time.Now()),
},
}
expiry := config.App.JWT.Expiry
switch {
case expiry > 0:
expireAt := time.Now().Add(expiry)
claims.ExpiresAt = jwt.NewNumericDate(expireAt)
case expiry == -1:
// 永不过期,ExpiresAt 设置为 nil
claims.ExpiresAt = nil
default:
// 默认过期时间,例如 1 小时
expireAt := time.Now().Add(time.Hour)
claims.ExpiresAt = jwt.NewNumericDate(expireAt)
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString([]byte(config.App.JWT.Secret))
}
// VerifyToken 验证并解析 JWT token
func VerifyToken(tokenString string) (*CustomClaims, error) {
signKey := []byte(config.App.JWT.Secret)
token, err := jwt.ParseWithClaims(tokenString, &CustomClaims{}, func(token *jwt.Token) (interface{}, error) {
// 校验签名算法
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, ErrTokenInvalid
}
return signKey, nil
})
if err != nil {
return nil, ErrTokenInvalid
}
claims, ok := token.Claims.(*CustomClaims)
if !ok || !token.Valid {
return nil, ErrTokenInvalid
}
// 检查过期:ExpiresAt 为 nil 时永不过期
if claims.ExpiresAt != nil && time.Now().After(claims.ExpiresAt.Time) {
return nil, ErrTokenExpired
}
return claims, nil
}