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
This commit is contained in:
92
internal/logger/middleware.go
Normal file
92
internal/logger/middleware.go
Normal file
@@ -0,0 +1,92 @@
|
||||
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()),
|
||||
)
|
||||
}
|
||||
}
|
||||
133
internal/logger/zap_logger.go
Normal file
133
internal/logger/zap_logger.go
Normal file
@@ -0,0 +1,133 @@
|
||||
package logger
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"go.uber.org/zap"
|
||||
"go.uber.org/zap/zapcore"
|
||||
"git.dcentral.systems/toolz/goplt/pkg/logger"
|
||||
)
|
||||
|
||||
const (
|
||||
// Context keys for extracting values from context
|
||||
requestIDKey = "request_id"
|
||||
userIDKey = "user_id"
|
||||
)
|
||||
|
||||
// zapLogger implements the Logger interface using zap.
|
||||
type zapLogger struct {
|
||||
zap *zap.Logger
|
||||
}
|
||||
|
||||
// NewZapLogger creates a new zap-based logger.
|
||||
// The format parameter determines the output format:
|
||||
// - "json": JSON format (production)
|
||||
// - "console": Human-readable format (development)
|
||||
func NewZapLogger(level string, format string) (logger.Logger, error) {
|
||||
var zapConfig zap.Config
|
||||
var zapLevel zapcore.Level
|
||||
|
||||
// Parse log level
|
||||
if err := zapLevel.UnmarshalText([]byte(level)); err != nil {
|
||||
zapLevel = zapcore.InfoLevel
|
||||
}
|
||||
|
||||
// Configure based on format
|
||||
if format == "json" {
|
||||
zapConfig = zap.NewProductionConfig()
|
||||
} else {
|
||||
zapConfig = zap.NewDevelopmentConfig()
|
||||
}
|
||||
|
||||
zapConfig.Level = zap.NewAtomicLevelAt(zapLevel)
|
||||
zapConfig.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
|
||||
|
||||
z, err := zapConfig.Build()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &zapLogger{zap: z}, nil
|
||||
}
|
||||
|
||||
// Debug logs a message at debug level.
|
||||
func (zl *zapLogger) Debug(msg string, fields ...logger.Field) {
|
||||
zl.zap.Debug(msg, convertFields(fields)...)
|
||||
}
|
||||
|
||||
// Info logs a message at info level.
|
||||
func (zl *zapLogger) Info(msg string, fields ...logger.Field) {
|
||||
zl.zap.Info(msg, convertFields(fields)...)
|
||||
}
|
||||
|
||||
// Warn logs a message at warning level.
|
||||
func (zl *zapLogger) Warn(msg string, fields ...logger.Field) {
|
||||
zl.zap.Warn(msg, convertFields(fields)...)
|
||||
}
|
||||
|
||||
// Error logs a message at error level.
|
||||
func (zl *zapLogger) Error(msg string, fields ...logger.Field) {
|
||||
zl.zap.Error(msg, convertFields(fields)...)
|
||||
}
|
||||
|
||||
// With creates a child logger with the specified fields.
|
||||
func (zl *zapLogger) With(fields ...logger.Field) logger.Logger {
|
||||
return &zapLogger{
|
||||
zap: zl.zap.With(convertFields(fields)...),
|
||||
}
|
||||
}
|
||||
|
||||
// WithContext creates a child logger with fields extracted from context.
|
||||
func (zl *zapLogger) WithContext(ctx context.Context) logger.Logger {
|
||||
fields := make([]logger.Field, 0)
|
||||
|
||||
// Extract request ID from context
|
||||
if requestID, ok := ctx.Value(requestIDKey).(string); ok && requestID != "" {
|
||||
fields = append(fields, zap.String("request_id", requestID))
|
||||
}
|
||||
|
||||
// Extract user ID from context
|
||||
if userID, ok := ctx.Value(userIDKey).(string); ok && userID != "" {
|
||||
fields = append(fields, zap.String("user_id", userID))
|
||||
}
|
||||
|
||||
if len(fields) == 0 {
|
||||
return zl
|
||||
}
|
||||
|
||||
return &zapLogger{
|
||||
zap: zl.zap.With(convertFields(fields)...),
|
||||
}
|
||||
}
|
||||
|
||||
// convertFields converts logger.Field to zap.Field.
|
||||
// Since Field is an alias for zap.Field, we can cast directly.
|
||||
func convertFields(fields []logger.Field) []zap.Field {
|
||||
if len(fields) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
zapFields := make([]zap.Field, 0, len(fields))
|
||||
for _, f := range fields {
|
||||
// Type assert to zap.Field
|
||||
if zf, ok := f.(zap.Field); ok {
|
||||
zapFields = append(zapFields, zf)
|
||||
} else {
|
||||
// Fallback: convert to Any field
|
||||
zapFields = append(zapFields, zap.Any("field", f))
|
||||
}
|
||||
}
|
||||
return zapFields
|
||||
}
|
||||
|
||||
// RequestIDKey returns the context key for request ID.
|
||||
// This is exported so modules can use it to set request IDs in context.
|
||||
func RequestIDKey() string {
|
||||
return requestIDKey
|
||||
}
|
||||
|
||||
// UserIDKey returns the context key for user ID.
|
||||
// This is exported so modules can use it to set user IDs in context.
|
||||
func UserIDKey() string {
|
||||
return userIDKey
|
||||
}
|
||||
Reference in New Issue
Block a user