MCP客户端-六边形架构
该项目遵循六边形架构(端口和适配器)模式,以维护干净、可测试和可维护的代码。
项目结构
/
├── main.go # Application entry point
├── adapters/ # External adapters
│ ├── api/ # HTTP API adapters
│ │ └── sample_handler.go # HTTP handlers
│ └── db/ # Database adapters
│ ├── connection.go # Database connection
│ └── sample_model/ # Model-specific repositories
│ └── sample_model_repo.go # Sample model repository
├── core/ # Core business logic
│ ├── domain/ # Domain models
│ │ └── sample_model.go # Sample domain model
│ ├── ports/ # Interface definitions
│ │ ├── db_port.go # Database port interface
│ │ └── sample_model_port.go # Sample model port interface
│ └── usecases/ # Business use cases
│ └── sample_business_flow/ # Sample business flow
│ └── sample_business_flow_usecase.go
└── go.mod # Go module definition建筑原理
六边形架构(端口和适配器)
- 核心:包含业务逻辑、域模型和端口接口
- 适配器:连接到数据库、API等的外部实现。
- 港口:定义核心和适配器之间契约的接口
关键组件
- 领域模型 (
core/domain/):没有外部依赖关系的纯业务实体 - 用例 (
core/usecases/):业务场景和工作流 - 港口 (
core/ports/):外部依赖关系的接口合同 - 适配器 (
adapters/):港口的具体实施
数据流
HTTP Request → API Handler → Use Case → Domain Logic → Port Interface → Repository Adapter → Database入门指南
- 安装依赖项:
go mod tidy- 构建项目:
go build .- 运行服务器:
./mcp_client服务器将在端口8080上启动,基本健康检查端点位于 /health.
开发指南
- 在用例中保留业务逻辑
- 通过端口接口使用依赖注入
- 为所有用例编写单元测试
- 保持适配器精简,专注于翻译
- 域模型不应有外部依赖关系
