Files
goplt/internal/logger/middleware.go
0x1d 4724a2efb5 feat: implement Epic 0 - Project Setup & Foundation
Implemented all 5 stories from Epic 0:

Story 0.1: Project Initialization
- Initialize Go module with path git.dcentral.systems/toolz/goplt
- Create complete directory structure (cmd/, internal/, pkg/, modules/, config/, etc.)
- Add comprehensive .gitignore for Go projects
- Create README.md with project overview and setup instructions

Story 0.2: Configuration Management System
- Define ConfigProvider interface in pkg/config
- Implement Viper-based configuration in internal/config
- Create configuration loader with environment support
- Add default, development, and production YAML config files

Story 0.3: Structured Logging System
- Define Logger interface in pkg/logger
- Implement Zap-based logger in internal/logger
- Add request ID middleware for Gin
- Create global logger export with convenience functions
- Support context-aware logging with request/user ID extraction

Story 0.4: CI/CD Pipeline
- Create GitHub Actions workflow for CI (test, lint, build, fmt)
- Add comprehensive Makefile with development commands
- Configure golangci-lint with reasonable defaults

Story 0.5: Dependency Injection and Bootstrap
- Create FX-based DI container in internal/di
- Implement provider functions for Config and Logger
- Create application entry point in cmd/platform/main.go
- Add lifecycle management with graceful shutdown

All acceptance criteria met:
- go build ./cmd/platform succeeds
- go test ./... runs successfully
- go mod verify passes
- Config loads from config/default.yaml
- Logger can be injected and used
- Application starts and shuts down gracefully
2025-11-05 12:21:15 +01:00

93 lines
2.5 KiB
Go

package logger
import (
"context"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"git.dcentral.systems/toolz/goplt/pkg/logger"
)
const (
// RequestIDHeader is the HTTP header name for request ID.
RequestIDHeader = "X-Request-ID"
)
// RequestIDMiddleware creates a Gin middleware that:
// 1. Generates a unique request ID for each request (or uses existing one from header)
// 2. Adds the request ID to the request context
// 3. Adds the request ID to the response headers
// 4. Makes the request ID available for logging
func RequestIDMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
// Check if request ID already exists in header
requestID := c.GetHeader(RequestIDHeader)
// Generate new request ID if not present
if requestID == "" {
requestID = uuid.New().String()
}
// Add request ID to context
ctx := context.WithValue(c.Request.Context(), RequestIDKey(), requestID)
c.Request = c.Request.WithContext(ctx)
// Add request ID to response header
c.Header(RequestIDHeader, requestID)
// Continue processing
c.Next()
}
}
// RequestIDFromContext extracts the request ID from the context.
func RequestIDFromContext(ctx context.Context) string {
if requestID, ok := ctx.Value(RequestIDKey()).(string); ok {
return requestID
}
return ""
}
// SetRequestID sets the request ID in the context.
func SetRequestID(ctx context.Context, requestID string) context.Context {
return context.WithValue(ctx, RequestIDKey(), requestID)
}
// SetUserID sets the user ID in the context.
func SetUserID(ctx context.Context, userID string) context.Context {
return context.WithValue(ctx, UserIDKey(), userID)
}
// UserIDFromContext extracts the user ID from the context.
func UserIDFromContext(ctx context.Context) string {
if userID, ok := ctx.Value(UserIDKey()).(string); ok {
return userID
}
return ""
}
// LoggingMiddleware creates a Gin middleware that logs HTTP requests.
// It uses the logger from the context and includes request ID.
func LoggingMiddleware(l logger.Logger) gin.HandlerFunc {
return func(c *gin.Context) {
// Get logger with context
log := l.WithContext(c.Request.Context())
// Log request
log.Info("HTTP request",
logger.String("method", c.Request.Method),
logger.String("path", c.Request.URL.Path),
logger.String("remote_addr", c.ClientIP()),
)
// Process request
c.Next()
// Log response
log.Info("HTTP response",
logger.Int("status", c.Writer.Status()),
logger.Int("size", c.Writer.Size()),
)
}
}