How bgbiao/gin-jwt-token works
Project type and purpose
• This is a Go-based RESTful API service built with the Gin framework.
• It exposes user-registration and login endpoints, issues JWT tokens, and protects “/auth/” routes behind JWT middleware.
• It persists user data in a MySQL database (via GORM).
File structure
• main.go: initializes Gin, loads config, registers routes and middleware, and starts HTTP server on :8081.
• api/config.go (+ test): loads config/config.ini (DB host, port, credentials).
• controller/user-token.go: handlers for /register, /login, and /auth/time.
• middleware/jwt.go: Gin middleware to validate and parse JWT on protected routes.
• model/user.go & utils.go (+ tests): defines User model and utility functions for DB operations (create user, authenticate).
• config/config.ini: externalizes DB config, enabling environment-specific overrides.
• Docker command in README spins up MySQL on 13306 to back the service.
README for additional insights
• Describes how to start MySQL in Docker, configure the config.ini, then run go run main.go.
• Lists three HTTP endpoints: POST /apis/v1/register, POST /apis/v1/login, GET /apis/v1/auth/time.
• Shows curl examples illustrating token issuance and protected-route access flow.
Main components and relationships
a. Client (Postman/curl/browsers)
• Sends HTTP requests to the API server.
b. API Server (Gin web engine)
• Config Loader (api/config) reads config.ini.
• Router:
• Public route group /apis/v1:
– POST /register → Controller.RegisterUser
– POST /login → Controller.Login (issues JWT token)
• Protected route group /apis/v1/auth:
– JWT Middleware (middleware/jwt.go) → Controller.GetDataByTime
• Controllers call into Model layer.
c. Model/Data Access Layer (model/*.go)
• Maps User struct to MySQL via GORM.
• Provides user-creation and authentication queries.
d. MySQL Database
• Running in Docker container on 127.0.0.1:13306.
• Stores users, credentials, any other persistent data.
e. JWT Token Service (jwt-go library)
• Used by Controller.Login to sign tokens, and by middleware to verify them.
Architectural patterns and design principles
• MVC-like separation: Controllers (HTTP handlers) vs. Models (DB operations).
• Layered architecture:
Config → Router & Middleware → Controller → Model → Database.
• Stateless authentication using JWT.
• Externalized configuration for environment flexibility.
• Dependency isolation:
• Gin for HTTP
• GORM for ORM
• jwt-go for token handling
• MySQL for persistence