Skip to main content

Routing System

Table of Contents

  1. Introduction
  2. Project Structure
  3. Core Components
  4. Architecture Overview
  5. Detailed Component Analysis
  6. Dependency Analysis
  7. Performance Considerations
  8. Troubleshooting Guide
  9. Conclusion
  10. Appendix

Introduction

This document targets API designers and backend developers, systematically organizes Gin-based HTTP routing system: including route registration mechanism, middleware chain execution order and parameter passing, parameter extraction and path variable binding, query parameter parsing, route prefix and version control strategy, as well as RESTful design principles and extension methods. The document takes "health check", "session management", "task management" three main routes as examples, combined with middleware chain (JWT, RBAC, RSA client signature) for in-depth analysis, and provides actionable routing design guide.

Project Structure

Routing system adopts layered and function domain division organization:

  • Route Registration Layer: Splits registration functions by domain in router package, centrally assembles during application startup phase.
  • Handler Layer: Implements specific business interfaces in handlers package, responsible for parameter parsing, calling use case services and returning responses.
  • Middleware Layer: Implements authentication and authorization logic in middlewares package, throughout request lifecycle.
  • Engine and Startup: Creates Gin engine, assembles middleware and routes in bootstrap, and starts HTTP service.

Core Components

Route Registrars

  • Health Check: RegisterHealthRoutes registers /health and /ready.
  • Session Management: RegisterSessionRoutes registers session creation, query, update, delete and data read.
  • Task Management: RegisterTaskRoutes reserved, current file is in commented state, not yet enabled.

Handlers

  • HealthHandler: Implements health and readiness check, reads application name and version from configuration.
  • SessionHandler: Implements session lifecycle and data read/write, uses Gin's path parameters and JSON/query binding.
  • TaskHandler: Reserved, current file is in commented state, not yet enabled.

Middleware

  • JWTAuthMiddleware: Parses Bearer token from Authorization header, validates signature and expiration, injects user principal to context.
  • RBACMiddleware: Executes subject-resource-action (RBAC) authorization based on Casbin.
  • RSAClientAuthMiddleware: Validates request body signature based on RSA-PSS, prevents replay and tampering.

Engine and Startup

  • App.NewApp creates gin.Default engine; App.Start starts HTTP server and gracefully shuts down.

Architecture Overview

The following diagram shows the full link from request entering engine to handler returning response, including middleware chain execution order and parameter passing.

Detailed Component Analysis

Health Check Route

URL Pattern and Method

  • GET /health: Health check
  • GET /ready: Liveness check

Parameters and Response

  • Response contains status, application name, version, timestamp and other information.

Configuration Source

  • Application name and version read from environment variables first, otherwise falls back to configuration file.

Handler Responsibilities

  • Reads configuration, constructs unified health/readiness response.

Session Route

URL Pattern and Method

  • POST /sessions: Create session
  • GET /sessions/:id: Query session by ID
  • PUT /sessions/:id: Update session data (requires JSON payload)
  • GET /sessions/:id/data: Read session specific data
  • DELETE /sessions/:id: Delete session

Parameter Extraction and Binding

  • Path Parameters: Extract through c.Param("id"), c.Param("key").
  • JSON Binding: Use ShouldBindJSON for structured validation of payload.
  • Query Parameters: Use ShouldBindQuery for structured validation of query parameters.

Middleware Chain

  • JWT Middleware: Ensures request carries valid token and injects user principal.
  • RBAC Middleware: Performs permission check on session-related resources.
  • RSA Middleware: Performs signature verification on requests from specific clients (optional).

Handler Responsibilities

  • Calls session use case service, handles business exceptions and returns standardized response.

Task Route (Reserved)

Current Status

  • Route registration and handler code are in commented state, not enabled.

Design Recommendations

  • Can refer to session route's RESTful design style, use plural nouns and path variables.
  • For asynchronous execution scenarios, provide synchronous/asynchronous two execution modes, and return appropriate HTTP status codes and response body.

Middleware Chain and Parameter Passing

Execution Order

  • During App initialization, Authorization aggregates middleware and mounts to Gin engine in order.
  • Typical order: JWT → RBAC → RSA (optional), finally reaches handler.

Parameter Passing

  • JWT middleware injects user principal to request context, for subsequent middleware and handler use.
  • RBAC middleware reads username from context, combines request path and method for authorization.
  • RSA middleware writes client identifier to context, convenient for audit and tracking.

Parameter Extraction and Binding

Path Parameters

  • Use c.Param("id") to extract path variables, ensure route definition matches handler.

JSON Binding

  • Use ShouldBindJSON for structured validation of request body, combine with struct tags (such as binding:"required") to improve robustness.

Query Parameters

  • Use ShouldBindQuery for structured validation of query parameters, supports default values and type conversion.

Error Handling

  • Returns 400 for binding errors, returns 4xx/5xx for business errors and includes clear error information.

Route Prefix and Version Control

Recommendations

  • Use Gin grouping (Group) to add prefix to routes, such as /api/v1.
  • Handle version number parsing and compatibility strategy uniformly in middleware layer.
  • For major changes, add new version prefix and keep old version for a period of time to ensure compatibility.

Current Project Status

  • Current routes do not use version prefix, recommend introducing version prefix during startup phase and handling uniformly in middleware.

RESTful Design Principles

Resource Naming

  • Use noun plural form (such as /sessions), avoid verbs and complex paths.

Action Mapping

  • POST: Create resource
  • GET: Read resource or list
  • PUT: Update resource
  • DELETE: Delete resource

Status Codes

  • Success: 200/201/204
  • Client Error: 400/401/403/404
  • Server Error: 500

Response Body

  • Unified structure, contains status, message and data fields, convenient for frontend consumption.

Dependency Analysis

Component Coupling

  • Route registrar only depends on handlers and configuration/use case services, maintains low coupling.
  • Handlers depend on use case services and Gin context, clear responsibilities.
  • Middleware depends on authentication and authorization libraries, strong independence.

External Dependencies

  • Gin: Routing and middleware framework.
  • JWT: Token parsing and validation.
  • Casbin: RBAC authorization.
  • RSA/PSS: Client signature verification and anti-replay.

Potential Circular Dependencies

  • No direct circular dependencies found; middleware and handlers are decoupled through interfaces.

Performance Considerations

Middleware Order

  • Place lightweight and failure-prone middleware (such as JWT/RBAC) first, reject illegal requests early, reduce subsequent overhead.

Cache and Deduplication

  • RSA middleware has built-in signature cache, can significantly reduce verification cost for duplicate requests.

Logging and Observability

  • Uniformly record request ID, user information and latency in middleware and handlers, convenient for problem diagnosis.

Timeout and Concurrency

  • Reasonably set Gin read/write timeout and connection pool size, avoid slow requests dragging down system.

Troubleshooting Guide

401 Unauthorized

  • Check if Authorization header is Bearer token format, confirm secret key and signature are valid.
  • Pay attention to JWT middleware's classification handling of token expiration, signature invalid and other errors.

403 Forbidden

  • Confirm if user principal and resource path/method satisfy Casbin policy.
  • Check if policy file and model configuration are correctly loaded.

400 Parameter Error

  • Check if request body JSON structure and query parameters satisfy binding rules.
  • Pay attention to error information from ShouldBindJSON/ShouldBindQuery.

5xx Server Error

  • View handler's handling of business exceptions and return codes.
  • Combine with logs to locate specific link.

Conclusion

This routing system uses Gin as core, adopts "route registrar + handler + middleware" clear layering, combined with JWT, RBAC, RSA client signature to form secure and reliable request chain. Health check and session management two main routes reflect best practices of RESTful design and parameter binding. Recommend introducing version prefix and unified error response specification on existing basis, and continuously improving task management routing and monitoring alerting system to support more complex business scenarios.

Appendix

Configuration Overview

  • Application Name and Version: Used for health check response.
  • Server Listen Address and Port: Used to start HTTP service.
  • Log Level and Output: Used for runtime observation.
  • CASBIN Model and Policy File Path: Used for permission control.

Authentication and Authorization Points

  • JWT token contains user ID and role information, convenient for RBAC and business side use.
  • RSA middleware supports time window, nonce and signature cache, balances security and performance.