HTTP Транспорт и роутинг
Relevant source files
The following files were used as context for generating this wiki page:
- cmd/app/main.go
- internal/core/middleware/middleware.go
- internal/features/tracks/transport/http/transport.go
- internal/features/playlists/transport/http/transport.go
- internal/features/users/transport/http/transport.go
- internal/features/tracks/transport/http/create.go
- internal/features/playlists/transport/http/create.go
The HTTP transport layer serves as the primary interface for external clients to interact with the Music Service. Built using the go-chi/chi router, it implements a modular and middleware-heavy architecture that separates cross-cutting concerns (authentication, logging, recovery) from feature-specific business logic. This system ensures that every request is properly identified, logged, and authorized before reaching the service layer.
The architecture follows a hierarchical structure where routes are grouped by access level: public routes, protected routes (requiring JWT authentication), and administrative routes (requiring specific roles). Each feature module (Tracks, Playlists, Users, etc.) defines its own set of routes which are then registered in the main application router.
Sources: cmd/app/main.go:130-181, README.md:126-150
Architecture Overview
The HTTP system is initialized in the main application entry point, where the router is configured with global middlewares and specific route groups.
The diagram illustrates the hierarchical request flow through various layers of middleware and route groupings.
Sources: cmd/app/main.go:130-179
Middleware Components
The service utilizes a robust chain of middlewares to handle request lifecycle events. These are divided into global utilities and security-focused filters.
| Middleware | File Path | Description |
|---|---|---|
CORS | middleware.go | Manages Cross-Origin Resource Sharing headers. |
RequestID | middleware.go | Injects/propagates a unique ID (UUID) for each request via X-Request-ID. |
Logger | middleware.go | Sets up context-aware logging with zap and request identifiers. |
Trace | middleware.go | Logs incoming request methods and measures processing latency. |
Recoverer | middleware.go | Captures panics and returns a structured 500 Internal Server Error. |
AuthMiddleware | middleware.go | Validates JWT Bearer tokens and extracts user claims into the context. |
RequireRole | middleware.go | Restricts access to handlers based on the user's role (e.g., "ADMIN"). |
Request Authentication Flow
The authentication process uses JWT claims stored in the request context to identify users and their subscription levels.
Sequence of JWT validation and claim extraction within the middleware layer.
Routing and Feature Transport
Each feature implements a Transport layer that defines its specific HTTP interface. Handlers are structured as structs that take their respective services as dependencies.
Feature Route Registration
Features provide a Routes() method returning a slice of server.Route objects, which contain the HTTP method, path, and handler function.
func (h *TrackHandler) Routes() []server.Route {
return []server.Route{
{Method: http.MethodGet, Path: "/tracks", Handler: h.ListTracks},
{Method: http.MethodGet, Path: "/tracks/{id}", Handler: h.GetTrack},
{Method: http.MethodPost, Path: "/tracks/{id}/play", Handler: h.PlayTrack},
}
}
Sources: internal/features/tracks/transport/http/transport.go:42-63
Administrative Routing
Some features define a separate AdminRoutes() set. In main.go, these are wrapped in an additional RequireRole("ADMIN") middleware.
r.Group(func(r chi.Router) {
r.Use(middleware.RequireRole("ADMIN"))
core_http_server.RegisterRoutes(r, trackHandler.AdminRoutes())
})
Sources: cmd/app/main.go:171-178, internal/features/tracks/transport/http/transport.go:65-81
Request Processing and Validation
Incoming requests are processed using standard core utilities to ensure consistency in data decoding and validation.
- Decoding: Requests use
core_http_request.DecodeAndValidateRequestto parse JSON bodies into structs with struct tag validation. - Path Parameters: Integer path parameters (like
{id}) are retrieved viacore_http_request.GetIntPathValue. - Query Parameters: Pagination or search parameters are handled via
core_http_request.GetIntQueryParam.
Example of handler logic:
func (h *TrackHandler) UpdateTrack(w http.ResponseWriter, r *http.Request) {
id, err := core_http_request.GetIntPathValue(r, "id")
var req CreateTrackRequest
if err := core_http_request.DecodeAndValidateRequest(r, &req); err != nil {
// Handle error
}
// Business logic call...
}
Sources: internal/features/tracks/transport/http/update.go:34-45, internal/features/tracks/transport/http/list_tracks.go:34-40
Server Lifecycle
The HTTP server is configured with specific timeouts to prevent resource exhaustion and supports graceful shutdown.
| Parameter | Value | Description |
|---|---|---|
ReadTimeout | 10s | Time limit for reading the entire request. |
WriteTimeout | 10s | Time limit for writing the response. |
IdleTimeout | 60s | Time limit for keeping idle connections open. |
The server listens for SIGINT and SIGTERM signals. Upon receiving a signal, it allows active requests up to 10 seconds to complete before forcing a shutdown.
Sources: cmd/app/main.go:183-221
The HTTP transport and routing system provides a structured, secure, and observable gateway to the Music Service. By utilizing a modular routing approach and centralized middleware, the project maintains clean separation between network protocols and business domain logic.