Initial commit: Basic project structure and dependencies

This commit is contained in:
2025-06-30 19:21:56 +08:00
commit 03e615a8fd
50 changed files with 11664 additions and 0 deletions

View File

@@ -0,0 +1,92 @@
package interfaces
import (
"context"
"time"
)
// Event 事件接口
type Event interface {
// 事件基础信息
GetID() string
GetType() string
GetVersion() string
GetTimestamp() time.Time
// 事件数据
GetPayload() interface{}
GetMetadata() map[string]interface{}
// 事件来源
GetSource() string
GetAggregateID() string
GetAggregateType() string
// 序列化
Marshal() ([]byte, error)
Unmarshal(data []byte) error
}
// EventHandler 事件处理器接口
type EventHandler interface {
// 处理器标识
GetName() string
GetEventTypes() []string
// 事件处理
Handle(ctx context.Context, event Event) error
// 处理器配置
IsAsync() bool
GetRetryConfig() RetryConfig
}
// DomainEvent 领域事件基础接口
type DomainEvent interface {
Event
// 领域特定信息
GetDomainVersion() string
GetCausationID() string
GetCorrelationID() string
}
// RetryConfig 重试配置
type RetryConfig struct {
MaxRetries int `json:"max_retries"`
RetryDelay time.Duration `json:"retry_delay"`
BackoffFactor float64 `json:"backoff_factor"`
MaxDelay time.Duration `json:"max_delay"`
}
// EventStore 事件存储接口
type EventStore interface {
// 事件存储
SaveEvent(ctx context.Context, event Event) error
SaveEvents(ctx context.Context, events []Event) error
// 事件查询
GetEvents(ctx context.Context, aggregateID string, fromVersion int) ([]Event, error)
GetEventsByType(ctx context.Context, eventType string, limit int) ([]Event, error)
GetEventsSince(ctx context.Context, timestamp time.Time, limit int) ([]Event, error)
// 快照支持
SaveSnapshot(ctx context.Context, aggregateID string, snapshot interface{}) error
GetSnapshot(ctx context.Context, aggregateID string) (interface{}, error)
}
// EventBus 事件总线接口
type EventBus interface {
// 事件发布
Publish(ctx context.Context, event Event) error
PublishBatch(ctx context.Context, events []Event) error
// 事件订阅
Subscribe(eventType string, handler EventHandler) error
Unsubscribe(eventType string, handler EventHandler) error
// 订阅管理
GetSubscribers(eventType string) []EventHandler
Start(ctx context.Context) error
Stop(ctx context.Context) error
}

View File

@@ -0,0 +1,152 @@
package interfaces
import (
"context"
"net/http"
"github.com/gin-gonic/gin"
)
// HTTPHandler HTTP处理器接口
type HTTPHandler interface {
// 处理器信息
GetPath() string
GetMethod() string
GetMiddlewares() []gin.HandlerFunc
// 处理函数
Handle(c *gin.Context)
// 权限验证
RequiresAuth() bool
GetPermissions() []string
}
// RESTHandler REST风格处理器接口
type RESTHandler interface {
HTTPHandler
// CRUD操作
Create(c *gin.Context)
GetByID(c *gin.Context)
Update(c *gin.Context)
Delete(c *gin.Context)
List(c *gin.Context)
}
// Middleware 中间件接口
type Middleware interface {
// 中间件名称
GetName() string
// 中间件优先级
GetPriority() int
// 中间件处理函数
Handle() gin.HandlerFunc
// 是否全局中间件
IsGlobal() bool
}
// Router 路由器接口
type Router interface {
// 路由注册
RegisterHandler(handler HTTPHandler) error
RegisterMiddleware(middleware Middleware) error
RegisterGroup(prefix string, middlewares ...gin.HandlerFunc) gin.IRoutes
// 路由管理
GetRoutes() gin.RoutesInfo
Start(addr string) error
Stop(ctx context.Context) error
// 引擎获取
GetEngine() *gin.Engine
}
// ResponseBuilder 响应构建器接口
type ResponseBuilder interface {
// 成功响应
Success(c *gin.Context, data interface{}, message ...string)
Created(c *gin.Context, data interface{}, message ...string)
// 错误响应
Error(c *gin.Context, err error)
BadRequest(c *gin.Context, message string, errors ...interface{})
Unauthorized(c *gin.Context, message ...string)
Forbidden(c *gin.Context, message ...string)
NotFound(c *gin.Context, message ...string)
Conflict(c *gin.Context, message string)
InternalError(c *gin.Context, message ...string)
// 分页响应
Paginated(c *gin.Context, data interface{}, pagination PaginationMeta)
}
// RequestValidator 请求验证器接口
type RequestValidator interface {
// 验证请求
Validate(c *gin.Context, dto interface{}) error
ValidateQuery(c *gin.Context, dto interface{}) error
ValidateParam(c *gin.Context, dto interface{}) error
// 绑定和验证
BindAndValidate(c *gin.Context, dto interface{}) error
}
// PaginationMeta 分页元数据
type PaginationMeta struct {
Page int `json:"page"`
PageSize int `json:"page_size"`
Total int64 `json:"total"`
TotalPages int `json:"total_pages"`
HasNext bool `json:"has_next"`
HasPrev bool `json:"has_prev"`
}
// APIResponse 标准API响应结构
type APIResponse struct {
Success bool `json:"success"`
Message string `json:"message"`
Data interface{} `json:"data,omitempty"`
Errors interface{} `json:"errors,omitempty"`
Pagination *PaginationMeta `json:"pagination,omitempty"`
Meta map[string]interface{} `json:"meta,omitempty"`
RequestID string `json:"request_id"`
Timestamp int64 `json:"timestamp"`
}
// HealthChecker 健康检查器接口
type HealthChecker interface {
// 健康检查
CheckHealth(ctx context.Context) HealthStatus
GetName() string
GetDependencies() []string
}
// HealthStatus 健康状态
type HealthStatus struct {
Status string `json:"status"` // UP, DOWN, DEGRADED
Message string `json:"message"`
Details map[string]interface{} `json:"details"`
CheckedAt int64 `json:"checked_at"`
ResponseTime int64 `json:"response_time_ms"`
}
// MetricsCollector 指标收集器接口
type MetricsCollector interface {
// HTTP指标
RecordHTTPRequest(method, path string, status int, duration float64)
RecordHTTPDuration(method, path string, duration float64)
// 业务指标
IncrementCounter(name string, labels map[string]string)
RecordGauge(name string, value float64, labels map[string]string)
RecordHistogram(name string, value float64, labels map[string]string)
// 自定义指标
RegisterCounter(name, help string, labels []string) error
RegisterGauge(name, help string, labels []string) error
RegisterHistogram(name, help string, labels []string, buckets []float64) error
// 指标导出
GetHandler() http.Handler
}

View File

@@ -0,0 +1,74 @@
package interfaces
import (
"context"
"time"
)
// Entity 通用实体接口
type Entity interface {
GetID() string
GetCreatedAt() time.Time
GetUpdatedAt() time.Time
}
// BaseRepository 基础仓储接口
type BaseRepository interface {
// 基础操作
Delete(ctx context.Context, id string) error
Count(ctx context.Context, options CountOptions) (int64, error)
Exists(ctx context.Context, id string) (bool, error)
// 软删除支持
SoftDelete(ctx context.Context, id string) error
Restore(ctx context.Context, id string) error
}
// Repository 通用仓储接口,支持泛型
type Repository[T any] interface {
BaseRepository
// 基础CRUD操作
Create(ctx context.Context, entity T) error
GetByID(ctx context.Context, id string) (T, error)
Update(ctx context.Context, entity T) error
// 批量操作
CreateBatch(ctx context.Context, entities []T) error
GetByIDs(ctx context.Context, ids []string) ([]T, error)
UpdateBatch(ctx context.Context, entities []T) error
DeleteBatch(ctx context.Context, ids []string) error
// 查询操作
List(ctx context.Context, options ListOptions) ([]T, error)
// 事务支持
WithTx(tx interface{}) Repository[T]
}
// ListOptions 列表查询选项
type ListOptions struct {
Page int `json:"page"`
PageSize int `json:"page_size"`
Sort string `json:"sort"`
Order string `json:"order"`
Filters map[string]interface{} `json:"filters"`
Search string `json:"search"`
Include []string `json:"include"`
}
// CountOptions 计数查询选项
type CountOptions struct {
Filters map[string]interface{} `json:"filters"`
Search string `json:"search"`
}
// CachedRepository 支持缓存的仓储接口
type CachedRepository[T Entity] interface {
Repository[T]
// 缓存操作
InvalidateCache(ctx context.Context, keys ...string) error
WarmupCache(ctx context.Context) error
GetCacheKey(id string) string
}

View File

@@ -0,0 +1,101 @@
package interfaces
import (
"context"
)
// Service 通用服务接口
type Service interface {
// 服务名称
Name() string
// 服务初始化
Initialize(ctx context.Context) error
// 服务健康检查
HealthCheck(ctx context.Context) error
// 服务关闭
Shutdown(ctx context.Context) error
}
// DomainService 领域服务接口,支持泛型
type DomainService[T Entity] interface {
Service
// 基础业务操作
Create(ctx context.Context, dto interface{}) (*T, error)
GetByID(ctx context.Context, id string) (*T, error)
Update(ctx context.Context, id string, dto interface{}) (*T, error)
Delete(ctx context.Context, id string) error
// 列表和查询
List(ctx context.Context, options ListOptions) ([]*T, error)
Search(ctx context.Context, query string, options ListOptions) ([]*T, error)
Count(ctx context.Context, options CountOptions) (int64, error)
// 业务规则验证
Validate(ctx context.Context, entity *T) error
ValidateCreate(ctx context.Context, dto interface{}) error
ValidateUpdate(ctx context.Context, id string, dto interface{}) error
}
// EventService 事件服务接口
type EventService interface {
Service
// 事件发布
Publish(ctx context.Context, event Event) error
PublishBatch(ctx context.Context, events []Event) error
// 事件订阅
Subscribe(eventType string, handler EventHandler) error
Unsubscribe(eventType string, handler EventHandler) error
// 异步处理
PublishAsync(ctx context.Context, event Event) error
}
// CacheService 缓存服务接口
type CacheService interface {
Service
// 基础缓存操作
Get(ctx context.Context, key string, dest interface{}) error
Set(ctx context.Context, key string, value interface{}, ttl ...interface{}) error
Delete(ctx context.Context, keys ...string) error
Exists(ctx context.Context, key string) (bool, error)
// 批量操作
GetMultiple(ctx context.Context, keys []string) (map[string]interface{}, error)
SetMultiple(ctx context.Context, data map[string]interface{}, ttl ...interface{}) error
// 模式操作
DeletePattern(ctx context.Context, pattern string) error
Keys(ctx context.Context, pattern string) ([]string, error)
// 缓存统计
Stats(ctx context.Context) (CacheStats, error)
}
// CacheStats 缓存统计信息
type CacheStats struct {
Hits int64 `json:"hits"`
Misses int64 `json:"misses"`
Keys int64 `json:"keys"`
Memory int64 `json:"memory"`
Connections int64 `json:"connections"`
}
// TransactionService 事务服务接口
type TransactionService interface {
Service
// 事务操作
Begin(ctx context.Context) (Transaction, error)
RunInTransaction(ctx context.Context, fn func(Transaction) error) error
}
// Transaction 事务接口
type Transaction interface {
Commit() error
Rollback() error
GetDB() interface{}
}