golang-yitisheng-server/server/common/context.go

42 lines
812 B
Go

// Package common 公共包
package common
import (
"server/modules/system/entity"
"github.com/gin-gonic/gin"
)
const ContextUserKey = "loginUser"
// GetLoginUser 从上下文获取当前登录用户
// 在Controller中使用: user := common.GetLoginUser(c)
func GetLoginUser(c *gin.Context) *entity.LoginUser {
value, exists := c.Get(ContextUserKey)
if !exists {
return nil
}
if user, ok := value.(*entity.LoginUser); ok {
return user
}
return nil
}
// GetLoginUserID 获取当前登录用户ID
func GetLoginUserID(c *gin.Context) string {
user := GetLoginUser(c)
if user != nil {
return user.ID
}
return ""
}
// GetLoginUsername 获取当前登录用户名
func GetLoginUsername(c *gin.Context) string {
user := GetLoginUser(c)
if user != nil {
return user.Username
}
return ""
}