Files
huangjin fe3ad20fe2 'init'
2026-06-29 17:34:59 +08:00

62 lines
1.3 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 从 gin.Context 提取中间件注入的数据 + 分页工具
package utils
import (
"strconv"
"github.com/gin-gonic/gin"
)
// GetUserID 从 Context 获取用户 ID支持 uint/float64/string 类型转换)
func GetUserID(c *gin.Context) uint {
userID, exists := c.Get("user_id")
if !exists {
return 0
}
switch v := userID.(type) {
case uint:
return v
case float64:
return uint(v)
case string:
id, _ := strconv.ParseUint(v, 10, 64)
return uint(id)
default:
return 0
}
}
// GetRoleCode 获取主角色编码
func GetRoleCode(c *gin.Context) string {
roleCode, exists := c.Get("role_code")
if !exists {
return ""
}
return roleCode.(string)
}
// HasRole 检查当前用户是否为指定角色
func HasRole(c *gin.Context, roleCode string) bool {
return GetRoleCode(c) == roleCode
}
// ParsePagination 解析分页参数,默认 page=1, pageSize=10, 最大 1000
func ParsePagination(c *gin.Context) (page, pageSize int) {
pageStr := c.DefaultQuery("page", "1")
pageSizeStr := c.DefaultQuery("page_size", "10")
page, _ = strconv.Atoi(pageStr)
pageSize, _ = strconv.Atoi(pageSizeStr)
if page < 1 {
page = 1
}
if pageSize < 1 || pageSize > 1000 {
pageSize = 10
}
return
}
// GetOffset 计算 SQL offset
func GetOffset(page, pageSize int) int {
return (page - 1) * pageSize
}