# gin-api **Repository Path**: go_36/gin-api ## Basic Information - **Project Name**: gin-api - **Description**: No description available - **Primary Language**: Go - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 1 - **Forks**: 0 - **Created**: 2026-04-24 - **Last Updated**: 2026-04-27 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # go-gin-api 搭建部署配置使用文档 > 本文档提供 go-gin-api 框架从零开始搭建、配置、部署到使用的完整指南。 --- ## 📋 目录 - [环境准备](#环境准备) - [项目搭建](#项目搭建) - [配置详解](#配置详解) - [数据库初始化](#数据库初始化) - [本地开发](#本地开发) - [生产部署](#生产部署) - [使用指南](#使用指南) - [监控与运维](#监控与运维) - [常见问题](#常见问题) --- ## 环境准备 ### 1. 系统要求 | 组件 | 最低版本 | 推荐版本 | |------|---------|---------| | Go | 1.18+ | 1.21+ | | MySQL | 5.7+ | 8.0+ | | Redis | 5.0+ | 7.0+ | | Git | 2.0+ | 最新版 | ### 2. 安装 Go ```bash # 下载 Go(以 Linux 为例) wget https://go.dev/dl/go1.21.5.linux-amd64.tar.gz # 解压到 /usr/local sudo tar -C /usr/local -xzf go1.21.5.linux-amd64.tar.gz # 配置环境变量 echo 'export PATH=$PATH:/usr/local/go/bin' >> ~/.bashrc echo 'export GOPROXY=https://goproxy.cn,direct' >> ~/.bashrc source ~/.bashrc # 验证安装 go version ``` ### 3. 安装 MySQL **方式一:Docker(推荐开发环境)** ```bash # 创建数据目录 mkdir -p ~/mysql/data ~/mysql/logs ~/mysql/conf # 创建配置文件 cat > ~/mysql/conf/my.cnf << 'EOF' [mysqld] character-set-server=utf8mb4 collation-server=utf8mb4_unicode_ci default-time-zone='+08:00' max_connections=200 innodb_buffer_pool_size=256M EOF # 启动 MySQL docker run -d \ --name mysql8 \ --restart always \ -p 3306:3306 \ -v ~/mysql/data:/var/lib/mysql \ -v ~/mysql/logs:/var/log/mysql \ -v ~/mysql/conf:/etc/mysql/conf.d \ -e MYSQL_ROOT_PASSWORD=123456 \ -e MYSQL_DATABASE=gin_api \ mysql:8.0 \ --default-authentication-plugin=mysql_native_password # 验证连接 docker exec -it mysql8 mysql -uroot -p123456 -e "SHOW DATABASES;" ``` **方式二:本地安装** ```bash # Ubuntu/Debian sudo apt update sudo apt install mysql-server-8.0 # CentOS/RHEL sudo yum install mysql-server # 启动服务 sudo systemctl start mysqld sudo systemctl enable mysqld # 安全配置 sudo mysql_secure_installation ``` ### 4. 安装 Redis **Docker 方式:** ```bash docker run -d \ --name redis7 \ --restart always \ -p 6379:6379 \ -v ~/redis/data:/data \ redis:7-alpine \ redis-server --appendonly yes --requirepass 123456 # 验证连接 docker exec -it redis7 redis-cli -a 123456 ping ``` ### 5. 安装开发工具 ```bash # 安装 swag 用于生成 Swagger 文档 go install github.com/swaggo/swag/cmd/swag@latest # 安装 air 用于热重载开发 go install github.com/cosmtrek/air@latest # 安装 gormgen 代码生成工具(项目内置) # 后续通过 go run cmd/gormgen 使用 ``` --- ## 项目搭建 ### 1. 克隆项目 ```bash # 克隆仓库 git clone https://github.com/xinliangnote/go-gin-api.git # 进入项目目录 cd go-gin-api # 查看项目结构 ls -la ``` ### 2. 安装依赖 ```bash # 下载所有依赖 go mod tidy # 验证依赖完整性 go mod verify # 查看依赖树 go mod graph | head -20 ``` ### 3. 项目结构说明 ``` go-gin-api/ ├── assets/ # 静态资源(前端页面、JS/CSS) │ ├── bootstrap/ # Bootstrap 资源 │ └── templates/ # HTML 模板 ├── cmd/ # 命令行工具 │ ├── gormgen/ # GORM 代码生成器 │ ├── handlergen/ # Handler 代码生成器 │ ├── mfmt/ # 代码格式化工具 │ └── mysqlmd/ # MySQL 元数据工具 ├── configs/ # 配置文件 │ ├── configs.go # 配置结构定义 │ ├── dev_configs.toml # 开发环境配置 │ ├── fat_configs.toml # 测试环境配置 │ ├── uat_configs.toml # 预发布环境配置 │ └── pro_configs.toml # 生产环境配置 ├── deployments/ # 部署配置 │ ├── loki/ # Loki 日志配置 │ └── prometheus/ # Prometheus 监控配置 ├── docs/ # Swagger 文档(自动生成) ├── internal/ # 内部代码 │ ├── api/ # API 层(Controller) │ ├── pkg/ # 内部工具包 │ ├── repository/ # 数据仓库层 │ ├── router/ # 路由配置 │ └── services/ # 业务逻辑层 ├── pkg/ # 公共包 │ ├── logger/ # 日志组件 │ ├── errors/ # 错误处理 │ └── ... ├── go.mod # Go 模块定义 ├── go.sum # 依赖锁定 ├── main.go # 程序入口 └── Dockerfile # Docker 构建文件 ``` --- ## 配置详解 ### 1. 配置文件结构 项目使用 TOML 格式配置文件,支持多环境: | 环境 | 配置文件 | 用途 | |------|---------|------| | dev | dev_configs.toml | 本地开发 | | fat | fat_configs.toml | 功能测试 | | uat | uat_configs.toml | 预发布 | | pro | pro_configs.toml | 生产环境 | ### 2. 完整配置示例 ```toml # ============================================ # MySQL 数据库配置 # ============================================ [mysql] # 读库配置(从库)- 用于查询操作 [mysql.read] addr = "127.0.0.1:3306" # 数据库地址 user = "root" # 用户名 pass = "123456" # 密码 name = "gin_api" # 数据库名 # 写库配置(主库)- 用于增删改操作 [mysql.write] addr = "127.0.0.1:3306" user = "root" pass = "123456" name = "gin_api" # 连接池配置 [mysql.base] maxOpenConn = 25 # 最大打开连接数 maxIdleConn = 25 # 最大空闲连接数 connMaxLifeTime = 60 # 连接最大生命周期(分钟) # ============================================ # Redis 缓存配置 # ============================================ [redis] addr = "127.0.0.1:6379" # Redis 地址 pass = "123456" # 密码(无密码留空) db = 0 # 数据库编号 maxRetries = 3 # 最大重试次数 poolSize = 10 # 连接池大小 minIdleConns = 5 # 最小空闲连接数 # ============================================ # 邮件服务配置(用于告警通知) # ============================================ [mail] host = "smtp.qq.com" # SMTP 服务器 port = 465 # 端口 user = "your-email@qq.com" # 发件人邮箱 pass = "your-auth-code" # 授权码(非密码) to = "admin@example.com" # 默认收件人 # ============================================ # HashIds 配置(用于 ID 加密) # ============================================ [hashids] secret = "your-secret-key" # 加密密钥 length = 12 # 生成的哈希长度 # ============================================ # 国际化配置 # ============================================ [language] local = "zh-CN" # 默认语言 ``` ### 3. 环境变量配置 除了配置文件,还可以通过环境变量设置: ```bash # 设置运行环境(dev/fat/uat/pro) export PROJECT_ENV=dev # 设置项目端口 export PROJECT_PORT=:9999 # 设置日志路径 export PROJECT_LOG_PATH=./logs ``` ### 4. 配置热更新 项目支持配置文件热更新(无需重启): ```go // configs/configs.go 中已实现 viper.WatchConfig() viper.OnConfigChange(func(e fsnotify.Event) { // 自动重新加载配置 viper.Unmarshal(config) }) ``` --- ## 数据库初始化 ### 1. 创建数据库 ```bash # 连接 MySQL mysql -uroot -p123456 # 创建数据库 CREATE DATABASE gin_api CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; # 创建专用用户(生产环境推荐) CREATE USER 'gin_api'@'%' IDENTIFIED BY 'your-password'; GRANT ALL PRIVILEGES ON gin_api.* TO 'gin_api'@'%'; FLUSH PRIVILEGES; ``` ### 2. 初始化数据表 项目首次启动会自动创建表结构,也可以通过以下方式手动初始化: ```bash # 方式一:自动安装(首次启动) go run main.go # 访问安装页面 open http://localhost:9999/install ``` ### 3. 数据库迁移 ```bash # 查看迁移状态 go run main.go migrate status # 执行迁移 go run main.go migrate up # 回滚迁移 go run main.go migrate down # 创建新迁移 go run main.go migrate create -name add_user_table ``` --- ## 本地开发 ### 1. 启动开发服务器 ```bash # 基础启动 go run main.go # 指定环境 go run main.go -e dev # 热重载开发(使用 air) air ``` ### 2. 开发工作流 ```bash # 1. 修改代码后,自动生成 Swagger 文档 swag init # 2. 格式化代码 go fmt ./... # 3. 运行测试 go test ./... # 4. 启动服务 go run main.go ``` ### 3. 代码生成 **生成 GORM 模型和 DAO:** ```bash # 生成所有表 go run cmd/gormgen/main.go # 生成指定表 go run cmd/gormgen/main.go -t user,order,product # 指定输出目录 go run cmd/gormgen/main.go -o internal/repository/mysql ``` **生成 Handler:** ```bash # 生成 CRUD Handler go run cmd/handlergen/main.go -t user ``` ### 4. 调试技巧 ```bash # 查看日志 tail -f logs/access.log tail -f logs/cron.log # 查看运行状态 curl http://localhost:9999/system/health # pprof 性能分析(非生产环境) go tool pprof http://localhost:9999/debug/pprof/profile go tool pprof http://localhost:9999/debug/pprof/heap ``` --- ## 生产部署 ### 1. 编译构建 ```bash # 清理旧构建 rm -rf dist/ mkdir -p dist # Linux AMD64 go mod tidy CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "-s -w" -o dist/go-gin-api-linux-amd64 main.go # Linux ARM64(云服务器常用) CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -ldflags "-s -w" -o dist/go-gin-api-linux-arm64 main.go # Windows CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -ldflags "-s -w" -o dist/go-gin-api-windows-amd64.exe main.go # macOS CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build -ldflags "-s -w" -o dist/go-gin-api-darwin-amd64 main.go ``` ### 2. Docker 部署 **单容器部署:** ```dockerfile # Dockerfile FROM golang:1.21-alpine AS builder WORKDIR /app COPY go.mod go.sum ./ RUN go mod download COPY . . RUN CGO_ENABLED=0 GOOS=linux go build -ldflags "-s -w" -o go-gin-api main.go FROM alpine:latest RUN apk --no-cache add ca-certificates tzdata tzdata WORKDIR /app COPY --from=builder /app/go-gin-api . COPY --from=builder /app/configs ./configs COPY --from=builder /app/assets ./assets # 非 root 用户运行 RUN adduser -D -g '' appuser USER appuser EXPOSE 9999 HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ CMD wget --no-verbose --tries=1 --spider http://localhost:9999/system/health || exit 1 CMD ["./go-gin-api"] ``` **构建并运行:** ```bash # 构建镜像 docker build -t go-gin-api:latest . # 运行容器 docker run -d \ --name go-gin-api \ --restart always \ -p 9999:9999 \ -v $(pwd)/configs:/app/configs \ -v $(pwd)/logs:/app/logs \ -e PROJECT_ENV=pro \ go-gin-api:latest ``` ### 3. Docker Compose 部署 **docker-compose.yml:** ```yaml version: '3.8' services: # MySQL 数据库 mysql: image: mysql:8.0 container_name: gin-api-mysql restart: always environment: MYSQL_ROOT_PASSWORD: 123456 MYSQL_DATABASE: gin_api TZ: Asia/Shanghai volumes: - mysql_data:/var/lib/mysql - ./init.sql:/docker-entrypoint-initdb.d/init.sql ports: - "3306:3306" command: > --default-authentication-plugin=mysql_native_password --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci healthcheck: test: ["CMD", "mysqladmin", "ping", "-h", "localhost"] timeout: 20s retries: 10 # Redis 缓存 redis: image: redis:7-alpine container_name: gin-api-redis restart: always command: redis-server --appendonly yes --requirepass 123456 volumes: - redis_data:/data ports: - "6379:6379" healthcheck: test: ["CMD", "redis-cli", "ping"] interval: 10s timeout: 3s retries: 5 # 应用服务 app: build: . container_name: gin-api-app restart: always depends_on: mysql: condition: service_healthy redis: condition: service_healthy environment: - PROJECT_ENV=pro - PROJECT_PORT=:9999 ports: - "9999:9999" volumes: - ./configs:/app/configs:ro - ./logs:/app/logs healthcheck: test: ["CMD", "wget", "--quiet", "--tries=1", "--spider", "http://localhost:9999/system/health"] interval: 30s timeout: 10s retries: 3 start_period: 40s # Nginx 反向代理 nginx: image: nginx:alpine container_name: gin-api-nginx restart: always ports: - "80:80" - "443:443" volumes: - ./nginx.conf:/etc/nginx/nginx.conf:ro - ./ssl:/etc/nginx/ssl:ro depends_on: - app volumes: mysql_data: redis_data: ``` **启动:** ```bash # 启动所有服务 docker-compose up -d # 查看日志 docker-compose logs -f app # 停止服务 docker-compose down # 完全清理(包括数据) docker-compose down -v ``` ### 4. Systemd 部署(Linux 服务器) 创建服务文件 `/etc/systemd/system/go-gin-api.service`: ```ini [Unit] Description=go-gin-api Service After=network.target mysql.service redis.service [Service] Type=simple User=www Group=www WorkingDirectory=/opt/go-gin-api ExecStart=/opt/go-gin-api/go-gin-api ExecReload=/bin/kill -HUP $MAINPID ExecStop=/bin/kill -SIGTERM $MAINPID Restart=always RestartSec=5 # 环境变量 Environment="PROJECT_ENV=pro" Environment="PROJECT_PORT=:9999" Environment="GIN_MODE=release" # 资源限制 LimitNOFILE=65535 LimitNPROC=4096 [Install] WantedBy=multi-user.target ``` **启动服务:** ```bash # 重载配置 sudo systemctl daemon-reload # 启动服务 sudo systemctl start go-gin-api # 设置开机自启 sudo systemctl enable go-gin-api # 查看状态 sudo systemctl status go-gin-api # 查看日志 sudo journalctl -u go-gin-api -f ``` ### 5. Nginx 配置 ```nginx upstream go_gin_api { server 127.0.0.1:9999 weight=5; # server 127.0.0.1:10000 weight=5; # 多实例负载均衡 keepalive 32; } server { listen 80; server_name api.example.com; # 强制 HTTPS return 301 https://$server_name$request_uri; } server { listen 443 ssl http2; server_name api.example.com; # SSL 证书 ssl_certificate /etc/nginx/ssl/api.example.com.crt; ssl_certificate_key /etc/nginx/ssl/api.example.com.key; ssl_session_timeout 1d; ssl_session_cache shared:SSL:50m; ssl_protocols TLSv1.2 TLSv1.3; ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256; ssl_prefer_server_ciphers off; # 日志 access_log /var/log/nginx/go-gin-api.access.log; error_log /var/log/nginx/go-gin-api.error.log; # 限流 limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s; limit_req zone=api_limit burst=20 nodelay; location / { proxy_pass http://go_gin_api; proxy_http_version 1.1; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_connect_timeout 60s; proxy_send_timeout 60s; proxy_read_timeout 60s; proxy_buffering on; proxy_buffer_size 4k; proxy_buffers 8 4k; } # 静态资源缓存 location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ { expires 30d; add_header Cache-Control "public, immutable"; } } ``` --- ## 使用指南 ### 1. 访问 Swagger 文档 ``` 开发环境:http://localhost:9999/swagger/index.html 生产环境:https://api.example.com/swagger/index.html ``` ### 2. 接口认证 **获取 Token:** ```bash curl -X POST http://localhost:9999/api/login \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "username=admin" \ -d "password=e10adc3949ba59abbe56e057f20f883e" # MD5(123456) ``` 响应: ```json { "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." } ``` **使用 Token:** ```bash curl -X GET http://localhost:9999/api/admin/info \ -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." ``` ### 3. 后台管理界面 ``` 访问地址:http://localhost:9999/ 默认账号:admin 默认密码:123456 ``` ### 4. 常用 API 示例 **创建管理员:** ```bash curl -X POST http://localhost:9999/api/admin \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $TOKEN" \ -d '{ "username": "newadmin", "password": "e10adc3949ba59abbe56e057f20f883e", "name": "新管理员", "mobile": "13800138000" }' ``` **分页查询:** ```bash curl -X GET "http://localhost:9999/api/admin?page=1&page_size=10" \ -H "Authorization: Bearer $TOKEN" ``` ### 5. 定时任务 项目内置定时任务调度,可在后台管理界面配置: ``` 访问:http://localhost:9999/admin/cron_task/list 支持 Cron 表达式,如: - 0 0 * * * * 每小时执行 - 0 0 0 * * * 每天零点执行 - 0 */5 * * * * 每5分钟执行 ``` --- ## 监控与运维 ### 1. Prometheus 监控 ``` 访问地址:http://localhost:9999/metrics ``` **关键指标:** | 指标名 | 说明 | |--------|------| | http_requests_total | HTTP 请求总数 | | http_request_duration_seconds | 请求处理耗时 | | gin_gin_api_requests_total | API 请求统计 | ### 2. 健康检查 ```bash # 系统健康检查 curl http://localhost:9999/system/health # 响应示例 { "timestamp": "2026-01-15T10:30:00+08:00", "environment": "pro", "host": "localhost:9999", "status": "ok" } ``` ### 3. 日志管理 **日志轮转配置:** ```yaml # 日志配置 log: level: info path: ./logs max_size: 100 # 单个文件 100MB max_backups: 30 # 保留 30 个备份 max_age: 30 # 保留 30 天 compress: true # 压缩旧日志 ``` **查看实时日志:** ```bash # 查看访问日志 tail -f logs/access.log | jq '.' # 查看错误日志 tail -f logs/error.log # 搜索特定 Trace ID grep "trace_id" logs/access.log | jq 'select(.trace_id == "xxx")' ``` ### 4. 告警配置 **邮件告警:** ```toml [mail] host = "smtp.qq.com" port = 465 user = "alert@example.com" pass = "your-auth-code" to = "admin@example.com,ops@example.com" ``` 触发条件: - Panic 异常 - 业务错误(标记为需要告警) - 自定义告警规则 --- ## 常见问题 ### Q1: 数据库连接失败 **现象:** ``` Error 1045: Access denied for user ``` **解决:** ```bash # 1. 检查配置 mysql -h127.0.0.1 -uroot -p123456 -e "SELECT 1" # 2. 检查用户权限 GRANT ALL PRIVILEGES ON gin_api.* TO 'root'@'%'; FLUSH PRIVILEGES; # 3. 检查防火墙 sudo ufw allow 3306 ``` ### Q2: Redis 连接失败 **现象:** ``` connection refused ``` **解决:** ```bash # 1. 检查 Redis 状态 docker exec -it redis7 redis-cli ping # 2. 检查密码 docker exec -it redis7 redis-cli -a 123456 ping # 3. 修改配置 [redis] pass = "123456" # 确保与 Redis 配置一致 ``` ### Q3: 端口被占用 **现象:** ``` bind: address already in use :9999 ``` **解决:** ```bash # 查找占用进程 lsof -i :9999 # 或修改端口 export PROJECT_PORT=:10000 go run main.go ``` ### Q4: 跨域问题 **解决:** ```go // 在 router/router.go 中启用 CORS mux, err := core.New(logger, core.WithEnableCors(), // 启用跨域 // ... ) ``` ### Q5: 性能优化 **数据库优化:** ```sql -- 添加索引 ALTER TABLE admin ADD INDEX idx_username (username); ALTER TABLE admin ADD INDEX idx_created_at (created_at); -- 查看慢查询 SHOW VARIABLES LIKE 'slow_query%'; ``` **应用优化:** ```toml [mysql.base] maxOpenConn = 50 # 根据并发调整 maxIdleConn = 25 connMaxLifeTime = 60 ``` --- ## 附录 ### A. 环境变量清单 | 变量名 | 说明 | 默认值 | |--------|------|--------| | PROJECT_ENV | 运行环境 | fat | | PROJECT_PORT | 服务端口 | :9999 | | PROJECT_DOMAIN | 项目域名 | http://127.0.0.1 | | PROJECT_LOG_PATH | 日志路径 | ./logs | ### B. 目录权限 ```bash # 创建目录并设置权限 mkdir -p logs uploads touch logs/access.log logs/cron.log chmod -R 755 logs uploads # Systemd 服务用户 sudo useradd -r -s /bin/false www sudo chown -R www:www /opt/go-gin-api ``` ### C. 升级指南 ```bash # 1. 备份数据 mysqldump -uroot -p gin_api > backup.sql # 2. 拉取新版本 git pull origin master # 3. 更新依赖 go mod tidy # 4. 重新编译 CGO_ENABLED=0 GOOS=linux go build -o go-gin-api main.go # 5. 平滑重启 sudo systemctl reload go-gin-api ``` --- *文档版本:v1.0 | 最后更新:2026-04-24*