Middleware
Relevant source files
The following files were used as context for generating this wiki page:
The middleware system in the Music Service provides a robust layer for handling cross-cutting concerns such as authentication, authorization, logging, request tracking, and panic recovery. These components are implemented as standard Go http.Handler wrappers, allowing them to be chained together to process requests before they reach the final business logic handlers.
The project utilizes the chi router to apply these middlewares both globally and to specific route groups, ensuring consistent behavior across different API segments like public authentication, user profiles, and administrative management.
Sources: internal/core/middleware/middleware.go, cmd/app/main.go:133-140
Global Request Lifecycle
Global middlewares are applied to every incoming request to provide infrastructure-level features. These include CORS headers for web compatibility, unique request identification for distributed tracing, and structured logging.
The diagram shows the sequential execution of global middlewares before the request reaches the router.
Sources: cmd/app/main.go:134-138
Infrastructure Middlewares
| Middleware | Function | Key Components |
|---|---|---|
| CORS | Configures Cross-Origin Resource Sharing. | Allows GET, POST, PUT, PATCH, DELETE, OPTIONS. |
| RequestID | Injects a unique UUID into request headers. | Header: X-Request-ID. |
| Logger | Injects a structured logger with request context. | Uses zap.Logger with request_id. |
| Trace | Logs request start, method, status code, and latency. | Uses response.ResponseWriter to capture status. |
| Recoverer | Catches panics during request handling. | Returns a 500 Internal Server Error via PanicResponse. |
Sources: internal/core/middleware/middleware.go:34-97
Security and Authorization
Security is enforced through a two-tiered middleware approach: standard JWT authentication followed by role-based access control (RBAC).
Authentication Flow
The AuthMiddleware extracts a JWT from the Authorization: Bearer <token> header, validates it against a secret key, and parses custom claims. If successful, these claims are injected into the request context.
Visual representation of the JWT validation and context injection process.
Sources: internal/core/middleware/middleware.go:107-135
Role-Based Access Control (RBAC)
The RequireRole middleware performs authorization by checking the Claims stored in the context by the authentication layer.
- Logic: It retrieves claims using
ClaimsKey. - Validation: It compares
claims.Roleagainst the required role (e.g.,ADMIN). - Response: If the role does not match or claims are missing, it returns a
403 Forbiddenresponse.
Sources: internal/core/middleware/middleware.go:137-150
Data Structures
Middleware Claims
The application uses a custom Claims struct to store user metadata within the JWT and the request context.
type Claims struct {
UserID int64 `json:"user_id"`
Email string `json:"email"`
Role string `json:"role"`
SubscriptionType string `json:"subscription_type"`
jwt.RegisteredClaims
}
Sources: internal/core/middleware/middleware.go:17-23
Integration with Routing
Middlewares are integrated into the application via the RegisterRoutes utility, which supports per-route middleware chaining, and through chi.Router's Use and Group methods.
| Route Group | Applied Middlewares |
|---|---|
| Global | CORS, RequestID, Logger, Trace, Recoverer |
| Protected | AuthMiddleware(secret) |
| Admin | AuthMiddleware(secret), RequireRole("ADMIN") |
Sources: cmd/app/main.go:134-168, internal/core/transport/http/server/route.go:18-26
Summary
The middleware layer acts as a gatekeeper and observer for the Music Service. By isolating infrastructure concerns like logging and recovery from security concerns like JWT validation and RBAC, the system ensures that business logic handlers only receive authorized and well-documented requests. This modularity allows for easy extension, such as adding rate limiting or additional telemetry, without modifying existing feature implementations.
Sources: internal/core/middleware/middleware.go, cmd/app/main.go