bindbox-game/CLAUDE.md

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 users
    • admin_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 rotation
    • jwtoken/: JWT token generation and parsing
    • redis/: Redis client initialization and management
    • otel/: OpenTelemetry integration for distributed tracing
    • wechat/: 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 schema
    • mfmt/: 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:

    1. JWT signature validity
    2. User exists and is active
    3. Token hash matches stored hash (prevents concurrent sessions)
    4. User login status is enabled
  • RBAC: Role-based access control for admin users. Two middleware patterns:

    • RequireAdminRole(): Checks if user has any role assigned
    • RequireAdminAction(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.go next to foo.go)
  • Run all tests: make test or go test -v --cover ./internal/...
  • Uses testify for assertions
  • Some tests use go-sqlmock for database mocking
  • Test database support: In-memory SQLite via testrepo_sqlite.go

Configuration

Configuration is managed by environment via TOML files:

  • dev_configs.toml: Development
  • fat_configs.toml: Feature testing
  • uat_configs.toml: User acceptance testing
  • pro_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

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 structs
  • internal/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

  1. Adding new API endpoints: Create handler in appropriate internal/api/ subdirectory, register route in internal/router/, and add business logic in corresponding service.

  2. Database changes: Create SQL migration file in migrations/ with date prefix (e.g., 20260207_description.sql), then regenerate GORM models with go run cmd/gormgen/main.go.

  3. Adding dependencies: Use go get for backend packages, pnpm add for frontend packages (in web/admin/).

  4. Debugging: Check logs in logs/ directory. Enable debug logging in logger initialization (see main.go).

  5. Environment-specific config: Modify appropriate TOML file in configs/ directory based on target environment.

  6. Code formatting: After making changes, run make fmt to format code. For import organization, use go run cmd/mfmt/main.go to group imports properly.

  7. 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.go has 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_SECRET environment variable matches config