Skip to content

Commit 656893c

Browse files
committed
refactor(context): use constants for context keys
This change introduces constants for all context keys used within the application. Previously, string literals were used directly, which is error-prone and makes it difficult to manage and update these keys. By centralizing these keys as constants, I improve code maintainability and reduce the risk of typos or inconsistent key usage across different parts of the codebase, particularly in the authentication middleware and request logging.
1 parent a1c7474 commit 656893c

File tree

5 files changed

+34
-18
lines changed

5 files changed

+34
-18
lines changed

auth.go

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ func (a *AuthMiddleware) HTTPContextFunc(next func(ctx context.Context, r *http.
5151
if !strings.HasPrefix(authHeader, "Bearer ") {
5252
a.logger.Warn("Missing or invalid authorization header from %s", r.RemoteAddr)
5353
// Set authentication error in context instead of failing the request
54-
ctx = context.WithValue(ctx, "auth_error", "missing_token")
54+
ctx = context.WithValue(ctx, authErrorKey, "missing_token")
5555
return next(ctx, r)
5656
}
5757

@@ -61,24 +61,24 @@ func (a *AuthMiddleware) HTTPContextFunc(next func(ctx context.Context, r *http.
6161
claims, err := a.validateJWT(token)
6262
if err != nil {
6363
a.logger.Warn("Invalid token from %s: %v", r.RemoteAddr, err)
64-
ctx = context.WithValue(ctx, "auth_error", "invalid_token")
64+
ctx = context.WithValue(ctx, authErrorKey, "invalid_token")
6565
return next(ctx, r)
6666
}
6767

6868
// Check if token is expired
6969
if time.Now().Unix() > claims.ExpiresAt {
7070
a.logger.Warn("Expired token from %s", r.RemoteAddr)
71-
ctx = context.WithValue(ctx, "auth_error", "expired_token")
71+
ctx = context.WithValue(ctx, authErrorKey, "expired_token")
7272
return next(ctx, r)
7373
}
7474

7575
a.logger.Info("Authenticated user %s (%s) from %s", claims.Username, claims.Role, r.RemoteAddr)
7676

7777
// Add user to request context
78-
ctx = context.WithValue(ctx, "authenticated", true)
79-
ctx = context.WithValue(ctx, "user_id", claims.UserID)
80-
ctx = context.WithValue(ctx, "username", claims.Username)
81-
ctx = context.WithValue(ctx, "user_role", claims.Role)
78+
ctx = context.WithValue(ctx, authenticatedKey, true)
79+
ctx = context.WithValue(ctx, userIDKey, claims.UserID)
80+
ctx = context.WithValue(ctx, usernameKey, claims.Username)
81+
ctx = context.WithValue(ctx, userRoleKey, claims.Role)
8282

8383
return next(ctx, r)
8484
}
@@ -185,25 +185,25 @@ func (a *AuthMiddleware) GenerateToken(userID, username, role string, expiration
185185

186186
// isAuthenticated checks if the request context contains valid authentication
187187
func isAuthenticated(ctx context.Context) bool {
188-
if auth, ok := ctx.Value("authenticated").(bool); ok && auth {
188+
if auth, ok := ctx.Value(authenticatedKey).(bool); ok && auth {
189189
return true
190190
}
191191
return false
192192
}
193193

194194
// getAuthError returns any authentication error from the context
195195
func getAuthError(ctx context.Context) string {
196-
if err, ok := ctx.Value("auth_error").(string); ok {
196+
if err, ok := ctx.Value(authErrorKey).(string); ok {
197197
return err
198198
}
199199
return ""
200200
}
201201

202202
// getUserInfo extracts user information from the authenticated context
203203
func getUserInfo(ctx context.Context) (userID, username, role string) {
204-
if userID, ok := ctx.Value("user_id").(string); ok {
205-
if username, ok := ctx.Value("username").(string); ok {
206-
if role, ok := ctx.Value("user_role").(string); ok {
204+
if userID, ok := ctx.Value(userIDKey).(string); ok {
205+
if username, ok := ctx.Value(usernameKey).(string); ok {
206+
if role, ok := ctx.Value(userRoleKey).(string); ok {
207207
return userID, username, role
208208
}
209209
}

context.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,4 +9,20 @@ const (
99
loggerKey contextKey = "logger"
1010
// configKey is the context key for the configuration
1111
configKey contextKey = "config"
12+
// authErrorKey is the context key for authentication errors
13+
authErrorKey contextKey = "auth_error"
14+
// authenticatedKey is the context key for authentication status
15+
authenticatedKey contextKey = "authenticated"
16+
// userIDKey is the context key for user ID
17+
userIDKey contextKey = "user_id"
18+
// usernameKey is the context key for username
19+
usernameKey contextKey = "username"
20+
// userRoleKey is the context key for user role
21+
userRoleKey contextKey = "user_role"
22+
// httpMethodKey is the context key for HTTP method
23+
httpMethodKey contextKey = "http_method"
24+
// httpPathKey is the context key for HTTP path
25+
httpPathKey contextKey = "http_path"
26+
// httpRemoteAddrKey is the context key for HTTP remote address
27+
httpRemoteAddrKey contextKey = "http_remote_addr"
1228
)

files.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,7 @@ func (fs *FileStore) UploadFile(ctx context.Context, req *FileUploadRequest) (*F
120120
// Validate URI before storing
121121
if fileInfo.URI == "" {
122122
logger.Error("Invalid URI for uploaded file: empty URI")
123-
return nil, errors.New("Invalid URI for uploaded file")
123+
return nil, errors.New("invalid URI for uploaded file")
124124
}
125125

126126
logger.Debug("Storing file info with URI: %s", fileInfo.URI)

gemini_server.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ func NewGeminiServer(ctx context.Context, config *Config) (*GeminiServer, error)
1515
}
1616

1717
if config.GeminiAPIKey == "" {
18-
return nil, errors.New("Gemini API key is required")
18+
return nil, errors.New("gemini API key is required")
1919
}
2020

2121
// Initialize the Gemini client

main.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -259,9 +259,9 @@ func createHTTPMiddleware(config *Config, logger Logger) server.HTTPContextFunc
259259
}
260260

261261
// Add request info to context
262-
ctx = context.WithValue(ctx, "http_method", r.Method)
263-
ctx = context.WithValue(ctx, "http_path", r.URL.Path)
264-
ctx = context.WithValue(ctx, "http_remote_addr", r.RemoteAddr)
262+
ctx = context.WithValue(ctx, httpMethodKey, r.Method)
263+
ctx = context.WithValue(ctx, httpPathKey, r.URL.Path)
264+
ctx = context.WithValue(ctx, httpRemoteAddrKey, r.RemoteAddr)
265265

266266
return ctx
267267
}
@@ -458,7 +458,7 @@ func wrapHandlerWithLogger(handler server.ToolHandlerFunc, toolName string, logg
458458

459459
// Check authentication for HTTP requests if enabled
460460
// Note: We need to check if this is an HTTP request and if auth is enabled
461-
if httpMethod, ok := ctx.Value("http_method").(string); ok && httpMethod != "" {
461+
if httpMethod, ok := ctx.Value(httpMethodKey).(string); ok && httpMethod != "" {
462462
// This is an HTTP request, check if auth is required
463463
// Get config from the context (we'll need to pass it through)
464464
if authError := getAuthError(ctx); authError != "" {

0 commit comments

Comments
 (0)