From 8b160bba153a4eeea4f1422b5c91a230ce758236 Mon Sep 17 00:00:00 2001 From: DJ Date: Wed, 21 Jan 2026 16:11:54 +0800 Subject: [PATCH] fix: use typed context key instead of string literal- Add UserContextKey constant to types package- Replace bare string 'user' with types.UserContextKey in auth middleware- Update user service to use UserContextKey for context value retrieval- Fixes staticcheck SA1029 warningThis prevents potential context key collisions. --- internal/application/service/user.go | 2 +- internal/middleware/auth.go | 4 ++-- internal/types/const.go | 2 ++ 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/internal/application/service/user.go b/internal/application/service/user.go index d5786b7e..60717a56 100644 --- a/internal/application/service/user.go +++ b/internal/application/service/user.go @@ -419,7 +419,7 @@ func (s *userService) RevokeToken(ctx context.Context, tokenString string) error // GetCurrentUser gets current user from context func (s *userService) GetCurrentUser(ctx context.Context) (*types.User, error) { - user, ok := ctx.Value("user").(*types.User) + user, ok := ctx.Value(types.UserContextKey).(*types.User) if !ok { return nil, errors.New("user not found in context") } diff --git a/internal/middleware/auth.go b/internal/middleware/auth.go index de943368..fc197b67 100644 --- a/internal/middleware/auth.go +++ b/internal/middleware/auth.go @@ -130,14 +130,14 @@ func Auth( // 存储用户和租户信息到上下文 c.Set(types.TenantIDContextKey.String(), targetTenantID) c.Set(types.TenantInfoContextKey.String(), tenant) - c.Set("user", user) + c.Set(types.UserContextKey.String(), user) c.Request = c.Request.WithContext( context.WithValue( context.WithValue( context.WithValue(c.Request.Context(), types.TenantIDContextKey, targetTenantID), types.TenantInfoContextKey, tenant, ), - "user", user, + types.UserContextKey, user, ), ) c.Next() diff --git a/internal/types/const.go b/internal/types/const.go index 15888683..3d4e790f 100644 --- a/internal/types/const.go +++ b/internal/types/const.go @@ -12,6 +12,8 @@ const ( RequestIDContextKey ContextKey = "RequestID" // LoggerContextKey is the context key for logger LoggerContextKey ContextKey = "Logger" + // UserContextKey is the context key for user information + UserContextKey ContextKey = "User" ) // String returns the string representation of the context key