跳到主要内容

开发环境搭建指南

🎯 环境要求

基础环境

  • 操作系统: macOS / Linux / Windows (WSL2)
  • Go版本: 1.25.4 或更高
  • Docker: 20.10+ 和 Docker Compose 2.0+
  • Git: 2.30+

开发工具

  • IDE: VS Code (推荐) 或 GoLand
  • 数据库工具: pgAdmin / DBeaver
  • API测试: Postman / Insomnia
  • 容器管理: Docker Desktop

🚀 快速开始

1. 克隆项目

git clone git@git.jingyun.design:jingyun/backend.git
cd backend

2. 安装依赖

# 安装Go依赖
go mod tidy

# 安装Protocol Buffers编译器 (macOS)
brew install protobuf

# 安装开发工具
make install-tools

3. 启动基础服务

# 启动依赖服务
docker-compose -f deployments/docker-compose.local.yml up -d

# 查看服务状态
docker-compose -f deployments/docker-compose.local.yml ps

4. 初始化数据库

# 数据库已通过Docker Compose自动创建
# 连接数据库验证
docker exec -it postgres-jingyun psql -U akita -d akita -c "\l"

# Ent ORM会自动处理表结构迁移
# 无需手动运行迁移命令

5. 生成代码

# 进入服务目录生成代码
cd services/gateway

# 生成所有代码
make all

# 或分步生成
make api # 生成API代码
make config # 生成配置代码
make wire # 生成Wire代码
make ent # 生成Ent代码 (如使用Ent)
make build # 编译服务

6. 启动服务

# 单独启动服务 (推荐)
cd services/gateway
make build
make run

# 或使用编译后的二进制文件
./bin/gateway -conf consul:8500

# 查看服务状态
docker-compose -f deployments/docker-compose.local.yml ps

🛠️ 开发工具配置

VS Code配置

创建 .vscode/settings.json:

{
"go.toolsManagement.checkForUpdates": "local",
"go.useLanguageServer": true,
"go.gopath": "",
"go.goroot": "",
"go.formatTool": "goimports",
"go.lintTool": "golangci-lint",
"go.lintFlags": ["--fast"],
"go.testFlags": ["-v"],
"go.coverOnSave": true,
"go.coverageDecorator": {
"type": "gutter",
"coveredHighlightColor": "rgba(64,128,64,0.5)",
"uncoveredHighlightColor": "rgba(128,64,64,0.25)"
}
}

推荐扩展:

  • Go (Google)
  • Docker
  • YAML Support
  • GitLens
  • Thunder Client (API测试)

Go环境配置

# 设置Go代理
export GOPROXY=https://goproxy.cn,direct
export GOSUMDB=sum.golang.google.cn

# 设置工作目录
export GOPATH=$HOME/go
export PATH=$PATH:$GOPATH/bin

📁 项目结构

backend/
├── api/ # API定义
├── pkg/ # 公共库
│ ├── api/ # 公共API定义
│ ├── grpc/ # gRPC客户端管理
│ ├── middleware/ # 中间件
│ ├── mq/ # 消息队列组件
│ └── utils/ # 工具函数
├── services/ # 微服务
│ ├── auth/ # 认证服务 (9001)
│ ├── user/ # 用户服务 (9002)
│ ├── tenant/ # 租户服务 (9003)
│ ├── agent/ # 智能体服务 (9004)
│ ├── payment/ # 支付服务 (9006)
│ ├── integration/ # 集成服务 (9007)
│ ├── cron/ # 定时任务服务 (9008)
│ └── gateway/ # 网关服务 (8000/9000)
├── deployments/ # 部署配置
├── docs/ # 文档
├── third_party/ # 第三方协议定义
└── Makefile # 构建脚本

🔧 开发流程

创建功能分支

# 从develop分支创建功能分支
git checkout develop
git pull origin develop
git checkout -b feature/new-feature

# 或从main分支创建hotfix分支
git checkout main
git pull origin main
git checkout -b hotfix/critical-bug

开发步骤

  1. 理解需求: 阅读相关文档和Issue
  2. 设计方案: 和团队讨论技术方案
  3. 编码实现: 按照编码规范开发
  4. 自测验证: 确保功能正常工作
  5. 更新文档: 同步更新相关文档
  6. 提交审核: 提交PR等待审核

本地测试

# 运行单元测试
make test

# 运行集成测试
make test-integration

# 运行所有测试
make test-all

# 生成测试覆盖率报告
make coverage

🐛 常见问题

环境问题

Go版本不兼容

# 检查Go版本
go version

# 安装正确版本
brew install go@1.25

# 或使用gvm管理版本
gvm install go1.25.4
gvm use go1.25.4

Docker服务启动失败

# 检查Docker状态
docker info

# 重启Docker服务
sudo systemctl restart docker

# 检查端口占用
lsof -i :5432 # PostgreSQL
lsof -i :6379 # Redis
lsof -i :5672 # RabbitMQ

数据库连接失败

# 检查数据库容器
docker-compose ps

# 查看数据库日志
docker-compose logs postgres

# 连接数据库测试
docker exec -it postgres-jingyun psql -U akita -d test

开发问题

代码生成失败

# 清理生成的代码
make clean

# 重新安装工具
make install-tools

# 重新生成代码
make all

服务启动失败

# 检查配置文件
cat conf/config.json

# 查看服务日志
./services/gateway/bin/gateway -conf config.json

# 检查端口占用
lsof -i :8000 # Gateway HTTP
lsof -i :9000 # Gateway gRPC

依赖下载失败

# 清理模块缓存
go clean -modcache

# 设置代理
export GOPROXY=https://goproxy.cn,direct

# 重新下载
go mod download

🔍 调试技巧

本地调试

// 使用Delve调试器
dlv debug ./services/gateway/main.go

# 或在VS Code中配置launch.json
{
"name": "Launch Package",
"type": "go",
"request": "launch",
"mode": "auto",
"program": "${workspaceFolder}/services/gateway/main.go"
}

日志调试

// 使用结构化日志
import "github.com/go-kratos/kratos/v2/log"

log.Info("Processing request",
"user_id", userID,
"action", action,
"timestamp", time.Now())

数据库调试

-- 查看表结构
\d table_name

-- 查看索引
\di table_name

-- 查看查询计划
EXPLAIN ANALYZE SELECT * FROM users WHERE id = 1;

📊 性能优化

本地性能测试

# 安装性能测试工具
go install github.com/pressly/goose/v3/cmd/goose@latest

# 运行基准测试
go test -bench=. -benchmem ./...

# 生成CPU性能分析
go test -cpuprofile=cpu.prof -bench=. ./...
go tool pprof cpu.prof

# 生成内存性能分析
go test -memprofile=mem.prof -bench=. ./...
go tool pprof mem.prof

数据库优化

-- 创建索引
CREATE INDEX idx_users_email ON users(email);
CREATE INDEX idx_orders_status ON orders(status);

-- 分析查询性能
EXPLAIN ANALYZE SELECT * FROM orders WHERE user_id = 1;

🧪 测试策略

单元测试

func TestUserService_CreateUser(t *testing.T) {
tests := []struct {
name string
input *CreateUserRequest
want *User
wantErr bool
}{
{
name: "valid user",
input: &CreateUserRequest{
Username: "testuser",
Email: "test@example.com",
},
want: &User{
Username: "testuser",
Email: "test@example.com",
},
wantErr: false,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := userService.CreateUser(context.Background(), tt.input)
if (err != nil) != tt.wantErr {
t.Errorf("CreateUser() error = %v, wantErr %v", err, tt.wantErr)
return
}
// 更多断言...
})
}
}

集成测试

func TestUserAPI_CreateUser(t *testing.T) {
// 设置测试环境
app := setupTestApp(t)
defer app.Cleanup()

// 测试API
resp, err := app.Client().Post("/api/v1/users", "application/json", strings.NewReader(`{
"username": "testuser",
"email": "test@example.com"
}`))

require.NoError(t, err)
require.Equal(t, 200, resp.StatusCode)
}

📚 参考资源

官方文档

开发工具

学习资源


📞 获取帮助

团队支持

  • 技术问题: 企业微信群或GitLab Issues
  • 环境问题: 联系运维开发
  • 流程问题: 咨询队长

常用命令速查

# 项目相关
make help # 查看所有命令
make clean # 清理构建文件
make build # 构建所有服务
make test # 运行测试
make lint # 代码检查

# Docker相关
docker-compose up -d # 启动服务
docker-compose down # 停止服务
docker-compose logs -f service # 查看日志
docker-compose exec service bash # 进入容器

# Git相关
git status # 查看状态
git add . # 添加所有变更
git commit -m "feat: add feature" # 提交变更
git push origin feature-branch # 推送分支

祝您开发愉快!如有问题,请随时联系团队 🚀