# Architecture ## Overview Bindbox Game follows a **layered monolith** architecture pattern built with Go and the Gin HTTP framework. The application serves as a backend for a blind box / lottery game platform with both a WeChat Mini Program client and a Vue 3 admin panel. ## Architectural Pattern **Layered Architecture (Handler → Service → Repository)** ``` HTTP Request ↓ [Router] → route matching + middleware (auth, RBAC, blacklist) ↓ [API Handler] → request parsing, validation, response formatting ↓ [Service Layer] → business logic, orchestration ↓ [Repository Layer] → GORM-based data access (MySQL read/write split) ↓ MySQL (Master/Slave) ``` ## Key Layers ### 1. Router Layer (`internal/router/`) - `router.go` — Single file defining all routes via `NewHTTPMux()` - Routes organized into groups: - `/api/internal` — Internal service calls (X-Internal-Key auth) - `/api/admin` — Admin panel (JWT + RBAC) - `/api/app` — Mini Program public endpoints (no auth) - `/api/app` (auth group) — Mini Program authenticated endpoints - `/api/public` — Public livestream endpoints (access code auth) - `/api/pay` — WeChat Pay callbacks (no auth) ### 2. Interceptor / Middleware Layer (`internal/router/interceptor/`) - `admin_auth.go` — JWT token verification for admin users - `admin_rbac.go` — Role-based access control with action-level permissions - `app_auth.go` — App user token verification - `blacklist.go` — Douyin user blacklist checking - `interceptor.go` — Base interceptor struct with shared dependencies ### 3. API Handler Layer (`internal/api/`) Organized by domain: - `admin/` — Admin panel handlers (largest, ~30+ files) - `activity/` — Lottery/game activity handlers - `app/` — Store, product, banner, category handlers - `game/` — Game ticket and minesweeper handlers - `pay/` — Payment handlers - `user/` — User management, orders, addresses - `task_center/` — Task center handlers - `common/` — Shared utilities (upload, openid) - `public/` — Public livestream handlers - `internal/` — Internal API handlers (Nakama integration) ### 4. Service Layer (`internal/service/`) Business logic organized by domain: - `activity/` — Activity CRUD, lottery processing, matching game, settlements, strategy pattern for draw types - `admin/` — Admin user management, login - `user/` — User management, orders, points, coupons, inventory, shipping, synthesis - `order/` — Order processing - `game/` — Game ticket management, minesweeper - `douyin/` — Douyin order sync, reward dispatching - `task_center/` — Task definitions, progress tracking, worker - `product/` — Product management - `finance/` — Financial operations, ledger - `channel/` — Marketing channel management - `title/` — User title/badge system - `banner/`, `sysconfig/`, `common/`, `snapshot/`, `recycle/`, `synthesis/`, `livestream/` ### 5. Repository Layer (`internal/repository/mysql/`) - `mysql.go` — Database connection management (read/write split via `Repo` interface) - `plugin.go` — GORM plugins - `model/*.gen.go` — Generated GORM models (do not edit) - `dao/*.gen.go` — Generated GORM DAOs (do not edit) - `task_center/models.go` — Task center specific models - `test_helper.go`, `testrepo_sqlite.go` — Test infrastructure ## Entry Point `main.go` initializes all infrastructure in order: 1. Config (Viper/TOML) 2. OpenTelemetry 3. MySQL (master + slave) 4. Logger (Zap-based with rotation) 5. Redis 6. HTTP server (Gin) 7. Background workers (settlement, expiration, order sync, dynamic config) 8. Graceful shutdown handler ## Data Flow ### Typical API Request Flow ``` Client → Gin Router → Middleware Chain → Handler → Service → Repository → MySQL ↓ Redis (cache, locks) ``` ### Background Task Flow ``` Scheduler (cron) → Service Method → Repository → MySQL ↓ External API (WeChat, Douyin) ``` ### Payment Flow ``` Client → Preorder API → WeChat Pay API → Client pays → WeChat Callback → Notify Handler → Order Service ``` ## Key Design Decisions | Decision | Rationale | |----------|-----------| | Read/write DB split | Performance: heavy reads go to slave, writes to master | | GORM code generation | Consistency: models and DAOs auto-generated from schema | | Custom `core.Context` wrapper | Standardized error handling, tracing, session management across all handlers | | Strategy pattern for lottery | Different draw types (standard, ichiban) share interface but have different logic | | Background workers in main process | Simplicity: no separate worker binary, uses goroutines | | JWT with hash verification | Security: stored token hash prevents concurrent sessions | ## Cross-Cutting Concerns - **Logging**: Zap-based with file rotation (`internal/pkg/logger/`) - **Tracing**: OpenTelemetry integration (`internal/pkg/otel/`) - **Error Codes**: 5-digit system in `internal/code/` (service level + module + specific) - **Alerts**: Alert notification system (`internal/alert/`) - **Metrics**: Prometheus metrics (`internal/metrics/`) ## External Service Boundaries The application integrates with multiple external services through dedicated packages in `internal/pkg/`: - WeChat Mini Program API (`wechat/`, `miniprogram/`) - WeChat Pay v3 API (`pay/`) - Douyin/TikTok API (`douyin/`) - Aliyun SMS (`sms/`) - Tencent COS (object storage) - OpenTelemetry collector --- *Generated: 2026-03-21*