11 KiB
Executable File
CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
Project Overview
Bindbox Game is a Go-based web application built with Gin framework for managing game activities, products, and user interactions. The project includes an admin panel (Vue 3) and integrates with WeChat Mini Program, WeChat Pay, Tencent COS, Douyin (TikTok), and Aliyun SMS services.
Module Name: bindbox-game (as defined in go.mod)
Note: This is part of a multi-project repository. Other related projects include bindbox-mini, douyin_game, and game. This CLAUDE.md file focuses on the bindbox_game directory.
Development Commands
Working Directory: Always work in /path/to/bindbox/bindbox_game/ directory. This is part of a monorepo that includes other projects (bindbox-mini, douyin_game, game).
Backend (Go)
# Run tests
make test # Run all tests
go test -v ./internal/service/... # Test specific package
go test -v -run TestFunctionName ./... # Run single test
# Format code
make fmt # Format all Go files
go run cmd/mfmt/main.go # Format with import grouping
# Run linter
make lint
# Build for different platforms
make build-win # Windows executable
make build-mac # MacOS executable
make build-linux # Linux executable
# Start the application
go run main.go # Development mode
ENV=dev go run main.go # Explicit environment
ENV=pro go run main.go # Production mode
# Generate Swagger documentation
make gen-swagger
# Serve Swagger UI locally
make serve-swagger # Opens at http://localhost:36666
Frontend (Vue 3 Admin Panel)
cd web/admin
# Install dependencies
pnpm install
# Start dev server (usually runs on http://localhost:5173)
pnpm dev
# Build for production
pnpm build
# Preview production build
pnpm preview
# Lint and fix
pnpm fix
# Format code
pnpm lint:prettier
# Type check
pnpm type-check
Database
# Run code generation for GORM models
go run cmd/gormgen/main.go
# Migrations are in migrations/ directory (SQL files)
# Apply them manually to your database
# Format Go code with import grouping (standard library, local module, third-party)
go run cmd/mfmt/main.go
Docker
# Build docker image
docker build -t zfc931912343/bindbox-game:v1.10 .
# Run with docker
docker run -d --name bindbox-game -p 9991:9991 zfc931912343/bindbox-game:v1.10
Architecture
Backend Structure
The backend follows a layered architecture pattern:
-
main.go: Application entry point. Initializes config, OpenTelemetry, MySQL, Redis, logger, HTTP server, and background tasks (scheduled settlement, order sync, expiration checks). -
configs/: Configuration management using Viper. Environment-specific TOML files (dev, fat, uat, pro). Configuration includes MySQL (read/write), Redis, JWT secrets, WeChat, WeChat Pay, Tencent COS, Aliyun SMS, Douyin integration, and OpenTelemetry settings. -
internal/api/: HTTP request handlers organized by domain (admin, user, game, activity, pay, wechat, etc.). Handlers parse requests, call services, and return responses. -
internal/service/: Business logic layer. Services contain domain logic and orchestrate repository calls. Key services: admin, user, game, activity, title, order, banner, sysconfig, douyin, task_center. -
internal/repository/mysql/: Data access layer using GORM. Contains generated DAO and model files (via gormgen). Supports read/write splitting with master-slave database configuration. -
internal/router/: HTTP routing setup with Gin. Defines routes and applies middleware/interceptors. -
internal/router/interceptor/: Middleware for authentication and authorization:admin_auth.go: JWT token verification for admin usersadmin_rbac.go: Role-based access control (RBAC) checking for admin actions
-
internal/pkg/: Shared utilities and helpers:core/: Custom Gin context wrapper with enhanced features (trace, logger, session info)logger/: Custom logger implementation (Zap-based) with file rotationjwtoken/: JWT token generation and parsingredis/: Redis client initialization and managementotel/: OpenTelemetry integration for distributed tracingwechat/: WeChat Mini Program integration (phone number, decryption)miniprogram/: WeChat Mini Program access token and subscribe message- Other utilities: validation, httpclient, timeutil, idgen, errors, etc.
-
internal/proposal/: Shared types and interfaces (session info, metrics, alerts, request logging). -
internal/code/: Error code definitions for API responses. Follows a 5-digit pattern:[service level (1)][module level (2)][specific error (2)]. Example:10101= service error (1) + user module (01) + invalid phone (01). -
cmd/: Command-line tools:gormgen/: Code generator for GORM models and DAOs from database schemamfmt/: Code formatter that organizes imports into three groups (standard library, local module, third-party packages)diagnose_ledger/: Diagnostic tool for ledger operations
Frontend Structure (Vue 3 Admin Panel)
Located in web/admin/:
- Vue 3 + TypeScript + Vite
- Element Plus UI framework
- Pinia for state management
- Vue Router for navigation
- Axios for HTTP requests
- Tailwind CSS for styling
Database
- MySQL with master-slave (read-write splitting) support
- GORM ORM with code generation (
gormgen) - Migrations in
migrations/directory (SQL files with date prefixes) - Generated models and DAOs in
internal/repository/mysql/
Authentication & Authorization
-
Admin JWT: Separate secret for admin users. Token includes user ID, role, and session info. Token verification checks:
- JWT signature validity
- User exists and is active
- Token hash matches stored hash (prevents concurrent sessions)
- User login status is enabled
-
RBAC: Role-based access control for admin users. Two middleware patterns:
RequireAdminRole(): Checks if user has any role assignedRequireAdminAction(mark): Checks if user's roles have permission for specific action mark
Background Tasks
Scheduled tasks initialized in main.go:
- Activity Settlement:
activitysvc.StartScheduledSettlement()- handles scheduled activity settlements - User Expiration Check:
usersvc.StartExpirationCheck()- checks and handles user data expirations - Douyin Order Sync:
douyinsvc.StartDouyinOrderSync()- syncs orders from Douyin platform - Dynamic Config:
syscfgsvc.InitGlobalDynamicConfig()- loads dynamic system configuration
External Integrations
- WeChat Mini Program: User authentication, phone number retrieval, subscribe messages
- WeChat Pay: Payment processing (API v3)
- Tencent COS: Object storage for file uploads
- Aliyun SMS: SMS notifications
- Douyin (TikTok): Order synchronization and product rewards
- OpenTelemetry: Distributed tracing and observability
Testing
- Tests located alongside source files (e.g.,
foo_test.gonext tofoo.go) - Run all tests:
make testorgo test -v --cover ./internal/... - Uses
testifyfor assertions - Some tests use
go-sqlmockfor database mocking - Test database support: In-memory SQLite via
testrepo_sqlite.go
Configuration
Configuration is managed by environment via TOML files:
dev_configs.toml: Developmentfat_configs.toml: Feature testinguat_configs.toml: User acceptance testingpro_configs.toml: Production
Set environment with ENV environment variable (defaults to dev).
JWT secrets can be overridden with environment variables:
ADMIN_JWT_SECRET: Overrides admin JWT secret from config
API Documentation
- Swagger annotations in code (see
main.gofor base config) - Generate:
make gen-swagger - View locally:
make serve-swagger(http://localhost:36666) - Production: http://127.0.0.1:9991/swagger/index.html (when running)
- Health check: http://127.0.0.1:9991/system/health
Code Generation
GORM Models
Run cmd/gormgen/main.go to generate GORM models and DAOs from database schema:
go run cmd/gormgen/main.go
This generates:
internal/repository/mysql/model/*.gen.go: Model structsinternal/repository/mysql/dao/*.gen.go: DAO query builders
Do not manually edit .gen.go files - they will be overwritten on next generation.
Important Patterns
Custom Context
The codebase uses core.Context (wrapper around gin.Context) throughout handlers. This provides:
- Enhanced request/response handling
- Integrated tracing and logging
- Session user info management
- Standardized error handling via
AbortWithError()
Always use core.Context in handlers, not gin.Context directly.
Error Handling
Use core.Error() to create business errors with HTTP status code, error code, and message:
err := core.Error(http.StatusBadRequest, code.ParamBindError, "Invalid parameters")
ctx.AbortWithError(err)
Error codes defined in internal/code/.
Response Patterns
Successful responses use ctx.Payload(data) to set response data. The framework handles JSON serialization and wrapping.
Service Layer Pattern
Services are initialized with logger and database repository:
svc := service.New(logger, dbRepo)
Services should contain business logic and call DAOs for data access. Keep handlers thin - move logic to services.
Working with This Codebase
-
Adding new API endpoints: Create handler in appropriate
internal/api/subdirectory, register route ininternal/router/, and add business logic in corresponding service. -
Database changes: Create SQL migration file in
migrations/with date prefix (e.g.,20260207_description.sql), then regenerate GORM models withgo run cmd/gormgen/main.go. -
Adding dependencies: Use
go getfor backend packages,pnpm addfor frontend packages (inweb/admin/). -
Debugging: Check logs in
logs/directory. Enable debug logging in logger initialization (seemain.go). -
Environment-specific config: Modify appropriate TOML file in
configs/directory based on target environment. -
Code formatting: After making changes, run
make fmtto format code. For import organization, usego run cmd/mfmt/main.goto group imports properly. -
Error codes: When defining new error codes in
internal/code/, follow the 5-digit pattern: service level (1) + module level (2) + specific error (2). Service level: 1=system error, 2=user error.
Common Issues \u0026 Troubleshooting
- Port already in use: Default port is 9991. Check if another instance is running:
lsof -i :9991 - Database connection errors: Verify MySQL is running and credentials in
configs/are correct - Redis connection errors: Ensure Redis is running on configured host/port
- GORM generation fails: Check database connectivity and ensure
cmd/gormgen/main.gohas correct DB credentials - Frontend build errors: Clear node_modules and reinstall:
cd web/admin && rm -rf node_modules && pnpm install - JWT token issues: If admin tokens are invalid, check
ADMIN_JWT_SECRETenvironment variable matches config