gateway

package
v0.0.0-...-a758801 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 8, 2025 License: GPL-2.0 Imports: 35 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ProtocolHTTP = "http"
	ProtocolGRPC = "grpc"
	ProtocolTCP  = "tcp"
	ProtocolUDP  = "udp"
)

支持的协议类型常量

Variables

This section is empty.

Functions

func ConfigureProtobuf

func ConfigureProtobuf(proxy *GRPCProxy, config *ProtobufConfiguration) error

ConfigureProtobuf 配置protobuf支持

func ExampleProtobufUsage

func ExampleProtobufUsage()

使用示例函数

Types

type BaseGateway

type BaseGateway struct {
	// contains filtered or unexported fields
}

BaseGateway 网关基础结构体,包含共享功能

func NewBaseGateway

func NewBaseGateway(config *BaseGatewayConfig, logger *zap.Logger) (*BaseGateway, error)

NewBaseGateway 创建基础网关实例

func (*BaseGateway) AddCompositeRoute

func (g *BaseGateway) AddCompositeRoute(route *Route, handler interface{}) error

AddCompositeRoute 添加组合路由到基础网关

func (*BaseGateway) AddRoute

func (g *BaseGateway) AddRoute(route *Route) error

AddRoute 添加路由到基础网关

func (*BaseGateway) Close

func (g *BaseGateway) Close() error

Close 关闭网关

func (*BaseGateway) GetCircuitBreakers

func (g *BaseGateway) GetCircuitBreakers() *circuitbreaker.CircuitBreakerManager

GetCircuitBreakers 获取熔断器管理器

func (*BaseGateway) GetCompositeHandler

func (g *BaseGateway) GetCompositeHandler(name string) (interface{}, bool)

GetCompositeHandler 获取组合处理器

func (*BaseGateway) GetDiscovery

func (g *BaseGateway) GetDiscovery() *discovery.Discovery

GetDiscovery 获取服务发现实例

func (*BaseGateway) GetMetrics

func (g *BaseGateway) GetMetrics() map[string]interface{}

GetMetrics 获取网关指标

func (*BaseGateway) GetMetricsCollector

func (g *BaseGateway) GetMetricsCollector() *metrics.MetricsCollector

GetMetricsCollector 获取指标收集器

func (*BaseGateway) GetRateLimiters

func (g *BaseGateway) GetRateLimiters() *ratelimiter.RateLimiterManager

GetRateLimiters 获取限流器管理器

func (*BaseGateway) GetReverseProxy

func (g *BaseGateway) GetReverseProxy(name string) (*httputil.ReverseProxy, bool)

GetReverseProxy 获取反向代理(已废弃,使用HTTP代理替代)

func (*BaseGateway) GetRoute

func (g *BaseGateway) GetRoute(name string) (*Route, bool)

GetRoute 获取路由配置

func (*BaseGateway) GetRoutes

func (g *BaseGateway) GetRoutes() map[string]*Route

GetRoutes 获取所有路由

func (*BaseGateway) GetTracer

func (g *BaseGateway) GetTracer() *tracing.Tracer

GetTracer 获取追踪器

type BaseGatewayConfig

type BaseGatewayConfig struct {
	DiscoveryEndpoints []string `json:"discoveryEndpoints"` // 服务发现端点
	Routes             []*Route `json:"routes"`             // 路由配置
	EnableMetrics      bool     `json:"enableMetrics"`      // 是否启用指标
	EnableTracing      bool     `json:"enableTracing"`      // 是否启用追踪
}

BaseGatewayConfig 基础网关配置

type CacheItem

type CacheItem struct {
	Data       []byte
	Timestamp  time.Time
	Expiration time.Time
}

CacheItem 缓存项

type CompositeStep

type CompositeStep struct {
	Name         string       `json:"name"`         // 步骤名称
	ServiceName  string       `json:"serviceName"`  // 目标服务名称
	Path         string       `json:"path"`         // 请求路径
	Method       string       `json:"method"`       // HTTP方法
	Protocol     string       `json:"protocol"`     // 协议类型
	InputMapper  InputMapper  `json:"inputMapper"`  // 输入映射配置
	OutputMapper OutputMapper `json:"outputMapper"` // 输出映射配置
	DependsOn    []string     `json:"dependsOn"`    // 依赖的步骤名称

	// protobuf相关配置
	UseProtobuf       bool   `json:"useProtobuf"`       // 是否使用protobuf格式
	InputMessageType  string `json:"inputMessageType"`  // protobuf输入消息类型
	OutputMessageType string `json:"outputMessageType"` // protobuf输出消息类型
}

CompositeStep 组合步骤配置

type ConnectionPool

type ConnectionPool struct {
	// contains filtered or unexported fields
}

ConnectionPool 连接池

func NewConnectionPool

func NewConnectionPool(maxSize int, logger *zap.Logger) *ConnectionPool

NewConnectionPool 创建连接池

func (*ConnectionPool) Close

func (p *ConnectionPool) Close() error

Close 关闭连接池

func (*ConnectionPool) GetConnection

func (p *ConnectionPool) GetConnection(serviceName string, createFunc func() (interface{}, error)) (interface{}, error)

GetConnection 从连接池获取连接

func (*ConnectionPool) ReturnConnection

func (p *ConnectionPool) ReturnConnection(serviceName string, conn interface{})

ReturnConnection 归还连接到连接池

type ErrorCode

type ErrorCode string

ErrorCode 错误码定义

const (
	// 通用错误
	ErrInternalServer     ErrorCode = "INTERNAL_SERVER_ERROR"
	ErrBadRequest         ErrorCode = "BAD_REQUEST"
	ErrUnauthorized       ErrorCode = "UNAUTHORIZED"
	ErrForbidden          ErrorCode = "FORBIDDEN"
	ErrNotFound           ErrorCode = "NOT_FOUND"
	ErrMethodNotAllowed   ErrorCode = "METHOD_NOT_ALLOWED"
	ErrTimeout            ErrorCode = "TIMEOUT"
	ErrTooManyRequests    ErrorCode = "TOO_MANY_REQUESTS"
	ErrServiceUnavailable ErrorCode = "SERVICE_UNAVAILABLE"

	// 网关特定错误
	ErrGatewayConfiguration ErrorCode = "GATEWAY_CONFIGURATION_ERROR"
	ErrServiceDiscovery     ErrorCode = "SERVICE_DISCOVERY_ERROR"
	ErrCircuitBreaker       ErrorCode = "CIRCUIT_BREAKER_TRIPPED"
	ErrRateLimitExceeded    ErrorCode = "RATE_LIMIT_EXCEEDED"
	ErrProxyError           ErrorCode = "PROXY_ERROR"
	ErrCompositeAPIError    ErrorCode = "COMPOSITE_API_ERROR"
	ErrProtocolNotSupported ErrorCode = "PROTOCOL_NOT_SUPPORTED"
)

type ErrorConfig

type ErrorConfig struct {
	ShowDetailedErrors bool `json:"showDetailedErrors"` // 是否显示详细错误信息
	LogStackTraces     bool `json:"logStackTraces"`     // 是否记录堆栈跟踪
	EnableRequestID    bool `json:"enableRequestID"`    // 是否启用请求ID
}

ErrorConfig 错误处理配置

type ErrorHandler

type ErrorHandler struct {
	// contains filtered or unexported fields
}

ErrorHandler 错误处理器

func NewErrorHandler

func NewErrorHandler(logger *zap.Logger, config *ErrorConfig) *ErrorHandler

NewErrorHandler 创建错误处理器

func (*ErrorHandler) ErrorMiddleware

func (h *ErrorHandler) ErrorMiddleware(next http.Handler) http.Handler

ErrorMiddleware 错误处理中间件

func (*ErrorHandler) HandleError

func (h *ErrorHandler) HandleError(w http.ResponseWriter, r *http.Request, err error)

HandleError 处理错误并返回适当的HTTP响应

func (*ErrorHandler) ValidateRouteConfig

func (h *ErrorHandler) ValidateRouteConfig(route *Route) []ValidationError

ValidateRouteConfig 验证路由配置

type ErrorResponse

type ErrorResponse struct {
	ErrorCode    string      `json:"error_code"`
	ErrorMessage string      `json:"error_message"`
	Details      interface{} `json:"details,omitempty"`
	RequestID    string      `json:"request_id,omitempty"`
	Timestamp    string      `json:"timestamp"`
}

ErrorResponse 错误响应结构

type GRPCProxy

type GRPCProxy struct {
	// contains filtered or unexported fields
}

GRPCProxy gRPC代理处理器

func NewGRPCProxy

func NewGRPCProxy(logger *zap.Logger, discovery *discovery.Discovery) *GRPCProxy

NewGRPCProxy 创建新的gRPC代理

func NewGRPCProxyWithConfig

func NewGRPCProxyWithConfig(config *GRPCProxyConfig) (*GRPCProxy, error)

NewGRPCProxyWithConfig 创建新的gRPC代理(使用配置结构)

func NewGRPCProxyWithProtobuf

func NewGRPCProxyWithProtobuf(logger *zap.Logger, discovery *discovery.Discovery, registry *protoregistry.Types) *GRPCProxy

NewGRPCProxyWithProtobuf 创建支持protobuf的gRPC代理

func (*GRPCProxy) Close

func (p *GRPCProxy) Close() error

Close 关闭所有gRPC连接

func (*GRPCProxy) ConvertInterfaceToProtobuf

func (p *GRPCProxy) ConvertInterfaceToProtobuf(data interface{}, messageType string) ([]byte, error)

ConvertInterfaceToProtobuf 将interface{}数据转换为protobuf格式

func (*GRPCProxy) ConvertJSONToProtobuf

func (p *GRPCProxy) ConvertJSONToProtobuf(jsonData []byte, messageType string) ([]byte, error)

ConvertJSONToProtobuf 将JSON数据转换为protobuf格式

func (*GRPCProxy) ConvertProtobufToJSON

func (p *GRPCProxy) ConvertProtobufToJSON(protoData []byte, messageType string) ([]byte, error)

ConvertProtobufToJSON 将protobuf数据转换为JSON格式

func (*GRPCProxy) CreateProtobufMessage

func (p *GRPCProxy) CreateProtobufMessage(messageType string) (proto.Message, error)

CreateProtobufMessage 创建protobuf消息实例

func (*GRPCProxy) DisableProtobuf

func (p *GRPCProxy) DisableProtobuf()

DisableProtobuf 禁用protobuf支持

func (*GRPCProxy) EnableProtobuf

func (p *GRPCProxy) EnableProtobuf(registry *protoregistry.Types)

EnableProtobuf 启用protobuf支持

func (*GRPCProxy) ForwardRequest

func (p *GRPCProxy) ForwardRequest(ctx context.Context, request *GRPCRequest) (*GRPCResponse, error)

ForwardRequest 转发gRPC请求(重构后版本) 使用分离的请求执行器和响应构建器

func (*GRPCProxy) GetMessageType

func (p *GRPCProxy) GetMessageType(name string) (protoreflect.MessageType, error)

GetMessageType 获取已注册的消息类型

func (*GRPCProxy) GetProtoJSONOptions

func (p *GRPCProxy) GetProtoJSONOptions() protojson.MarshalOptions

GetProtoJSONOptions 获取当前的protobuf到JSON序列化选项

func (*GRPCProxy) GetSupportedFormats

func (p *GRPCProxy) GetSupportedFormats() []string

GetSupportedFormats 获取支持的请求格式

func (*GRPCProxy) HealthCheck

func (p *GRPCProxy) HealthCheck() *HealthStatus

HealthCheck 健康检查(测试文件使用的方法)

func (*GRPCProxy) ListRegisteredMessageTypes

func (p *GRPCProxy) ListRegisteredMessageTypes() []string

ListRegisteredMessageTypes 列出所有已注册的消息类型

func (*GRPCProxy) MarshalProtobufToJSON

func (p *GRPCProxy) MarshalProtobufToJSON(msg proto.Message) ([]byte, error)

MarshalProtobufToJSON 将protobuf消息序列化为JSON

func (*GRPCProxy) ProxyHTTPRequest

func (p *GRPCProxy) ProxyHTTPRequest(w http.ResponseWriter, r *http.Request, route *Route)

ProxyHTTPRequest 代理HTTP到gRPC的请求

func (*GRPCProxy) ProxyRequestWithFormat

func (p *GRPCProxy) ProxyRequestWithFormat(ctx context.Context, serviceName, method string, reqData []byte, format string) ([]byte, error)

ProxyRequestWithFormat 代理gRPC请求,支持指定数据格式

func (*GRPCProxy) RegisterMessageType

func (p *GRPCProxy) RegisterMessageType(name string, msgType protoreflect.MessageType) error

RegisterMessageType 注册单个protobuf消息类型

func (*GRPCProxy) RegisterMessageTypes

func (p *GRPCProxy) RegisterMessageTypes(types map[string]protoreflect.MessageType) error

RegisterMessageTypes 批量注册protobuf消息类型

func (*GRPCProxy) SetProtoJSONOptions

func (p *GRPCProxy) SetProtoJSONOptions(options protojson.MarshalOptions)

SetProtoJSONOptions 设置protobuf到JSON的序列化选项

func (*GRPCProxy) UnmarshalJSONToProtobuf

func (p *GRPCProxy) UnmarshalJSONToProtobuf(data []byte, messageType string) (proto.Message, error)

UnmarshalJSONToProtobuf 将JSON反序列化为protobuf消息

func (*GRPCProxy) ValidateProtobufMessage

func (p *GRPCProxy) ValidateProtobufMessage(msg proto.Message) error

ValidateProtobufMessage 验证protobuf消息的有效性

type GRPCProxyConfig

type GRPCProxyConfig struct {
	Discovery      *discovery.Discovery // 服务发现接口
	Logger         *zap.Logger          // 日志记录器
	MaxConnections int                  // 最大连接数
	RequestTimeout time.Duration        // 请求超时时间
	RetryCount     int                  // 重试次数
	RetryDelay     time.Duration        // 重试延迟
}

GRPCProxyConfig gRPC代理配置

type GRPCRequest

type GRPCRequest struct {
	ServiceName string            `json:"service_name"`
	MethodName  string            `json:"method_name"`
	Message     interface{}       `json:"message"`
	Format      MessageFormat     `json:"format"`
	Metadata    map[string]string `json:"metadata"`
}

GRPCRequest gRPC请求结构

type GRPCRequestExecutor

type GRPCRequestExecutor struct {
	// contains filtered or unexported fields
}

GRPCRequestExecutor gRPC请求执行器 负责执行gRPC请求的核心逻辑 将请求执行过程与响应构建过程分离 新增结构体,用于封装gRPC请求执行逻辑

func NewGRPCRequestExecutor

func NewGRPCRequestExecutor(proxy *GRPCProxy) *GRPCRequestExecutor

NewGRPCRequestExecutor 创建新的gRPC请求执行器

func (*GRPCRequestExecutor) ExecuteRequest

func (e *GRPCRequestExecutor) ExecuteRequest(ctx context.Context, request *GRPCRequest) ([]byte, error)

ExecuteRequest 执行gRPC请求 专注于请求的执行过程,返回原始响应数据和错误

type GRPCResponse

type GRPCResponse struct {
	Message interface{} `json:"message"`
	Status  codes.Code  `json:"status"`
	Error   string      `json:"error,omitempty"`
}

GRPCResponse gRPC响应结构

type GRPCResponseBuilder

type GRPCResponseBuilder struct {
}

GRPCResponseBuilder gRPC响应构建器 负责构建标准化的gRPC响应 将响应构建过程与请求执行过程分离 新增结构体,用于封装gRPC响应构建逻辑

func NewGRPCResponseBuilder

func NewGRPCResponseBuilder() *GRPCResponseBuilder

NewGRPCResponseBuilder 创建新的gRPC响应构建器

func (*GRPCResponseBuilder) BuildErrorResponse

func (b *GRPCResponseBuilder) BuildErrorResponse(err error) (*GRPCResponse, error)

BuildErrorResponse 构建错误响应 专注于错误响应的构建过程

func (*GRPCResponseBuilder) BuildSuccessResponse

func (b *GRPCResponseBuilder) BuildSuccessResponse(responseData []byte) *GRPCResponse

BuildSuccessResponse 构建成功响应 专注于成功响应的构建过程

type Gateway

type Gateway struct {
	*BaseGateway
	// contains filtered or unexported fields
}

Gateway API网关

func NewGateway

func NewGateway(config *GatewayConfig, logger *zap.Logger) (*Gateway, error)

NewGateway 创建新的API网关

func (*Gateway) AddCompositeRoute

func (g *Gateway) AddCompositeRoute(route *Route) error

AddCompositeRoute 添加组合路由

func (*Gateway) AddRoute

func (g *Gateway) AddRoute(route *Route) error

AddRoute 添加路由

func (*Gateway) Start

func (g *Gateway) Start() error

Start 启动网关

func (*Gateway) Stop

func (g *Gateway) Stop() error

Stop 停止网关

type GatewayConfig

type GatewayConfig struct {
	Port               int      `json:"port"`               // 监听端口
	DiscoveryEndpoints []string `json:"discoveryEndpoints"` // 服务发现端点
	Routes             []*Route `json:"routes"`             // 路由配置
	EnableMetrics      bool     `json:"enableMetrics"`      // 是否启用指标
	EnableTracing      bool     `json:"enableTracing"`      // 是否启用追踪
}

GatewayConfig 网关配置

type GatewayError

type GatewayError struct {
	Code           ErrorCode
	Message        string
	HTTPStatusCode int
	OriginalError  error
}

GatewayError 网关特定错误类型

func NewGatewayError

func NewGatewayError(code ErrorCode, message string, statusCode int) *GatewayError

NewGatewayError 创建新的网关错误

func WrapGatewayError

func WrapGatewayError(code ErrorCode, message string, statusCode int, originalErr error) *GatewayError

WrapGatewayError 包装现有错误为网关错误

func (*GatewayError) Error

func (e *GatewayError) Error() string

Error 实现error接口

func (*GatewayError) Unwrap

func (e *GatewayError) Unwrap() error

Unwrap 实现错误解包

type GinGateway

type GinGateway struct {
	*BaseGateway
	// contains filtered or unexported fields
}

GinGateway Gin框架的API网关

func NewGinGateway

func NewGinGateway(config *GinGatewayConfig, logger *zap.Logger) (*GinGateway, error)

NewGinGateway 创建新的Gin API网关

func (*GinGateway) AddCompositeRoute

func (g *GinGateway) AddCompositeRoute(route *Route) error

AddCompositeRoute 添加组合路由

func (*GinGateway) AddGinMiddleware

func (g *GinGateway) AddGinMiddleware(middleware gin.HandlerFunc)

AddGinMiddleware 添加自定义Gin中间件

func (*GinGateway) AddGinRoute

func (g *GinGateway) AddGinRoute(method, path string, handler gin.HandlerFunc)

AddGinRoute 添加自定义Gin路由

func (*GinGateway) AddRoute

func (g *GinGateway) AddRoute(route *Route) error

AddRoute 添加路由到Gin网关

func (*GinGateway) Start

func (g *GinGateway) Start() error

Start 启动Gin网关

func (*GinGateway) Stop

func (g *GinGateway) Stop() error

Stop 停止Gin网关

type GinGatewayConfig

type GinGatewayConfig struct {
	Port               int      `json:"port"`               // 监听端口
	DiscoveryEndpoints []string `json:"discoveryEndpoints"` // 服务发现端点
	Routes             []*Route `json:"routes"`             // 路由配置
	EnableMetrics      bool     `json:"enableMetrics"`      // 是否启用指标
	EnableTracing      bool     `json:"enableTracing"`      // 是否启用追踪
	GinMode            string   `json:"ginMode"`            // Gin模式: debug, release, test
}

GinGatewayConfig Gin网关配置

type HealthStatus

type HealthStatus struct {
	IsHealthy bool   `json:"is_healthy"`
	Message   string `json:"message"`
}

HealthStatus 健康状态结构

type HttpProxy

type HttpProxy struct {
	// contains filtered or unexported fields
}

HttpProxy HTTP代理处理器

func NewHttpProxy

func NewHttpProxy(logger *zap.Logger, discovery *discovery.Discovery) *HttpProxy

NewHttpProxy 创建新的HTTP代理

func (*HttpProxy) Close

func (p *HttpProxy) Close() error

Close 关闭所有HTTP代理

func (*HttpProxy) ProxyRequest

func (p *HttpProxy) ProxyRequest(ctx context.Context, serviceName, method, path string, headers map[string]string, body []byte) (*http.Response, error)

ProxyRequest 代理HTTP请求

type InputMapper

type InputMapper struct {
	Type     string                 `json:"type"`     // 映射类型: static, dynamic, template
	Template string                 `json:"template"` // 模板字符串
	Params   map[string]interface{} `json:"params"`   // 参数映射
}

InputMapper 输入映射配置

type MessageFormat

type MessageFormat string

MessageFormat 消息格式枚举

const (
	FormatProtobuf MessageFormat = "protobuf"
	FormatJSON     MessageFormat = "json"
	FormatAuto     MessageFormat = "auto"
)

type OutputMapper

type OutputMapper struct {
	Type     string `json:"type"`     // 映射类型: json_path, template
	Path     string `json:"path"`     // JSON路径
	Template string `json:"template"` // 模板字符串
}

OutputMapper 输出映射配置

type PerformanceConfig

type PerformanceConfig struct {
	EnableCaching        bool          `json:"enableCaching"`        // 是否启用缓存
	CacheTTL             time.Duration `json:"cacheTTL"`             // 缓存生存时间
	MaxCacheSize         int64         `json:"maxCacheSize"`         // 最大缓存大小
	EnableConnectionPool bool          `json:"enableConnectionPool"` // 是否启用连接池
	MaxConnections       int           `json:"maxConnections"`       // 最大连接数
	ConnectionTimeout    time.Duration `json:"connectionTimeout"`    // 连接超时时间
	EnableCompression    bool          `json:"enableCompression"`    // 是否启用压缩
}

PerformanceConfig 性能配置

type PerformanceOptimizer

type PerformanceOptimizer struct {
	// contains filtered or unexported fields
}

PerformanceOptimizer 性能优化器

func NewPerformanceOptimizer

func NewPerformanceOptimizer(logger *zap.Logger) *PerformanceOptimizer

NewPerformanceOptimizer 创建性能优化器

func (*PerformanceOptimizer) CachingMiddleware

func (p *PerformanceOptimizer) CachingMiddleware(config *PerformanceConfig) func(http.Handler) http.Handler

CachingMiddleware 缓存中间件

func (*PerformanceOptimizer) CompressionMiddleware

func (p *PerformanceOptimizer) CompressionMiddleware(config *PerformanceConfig) func(http.Handler) http.Handler

CompressionMiddleware 压缩中间件

func (*PerformanceOptimizer) MonitorPerformance

func (p *PerformanceOptimizer) MonitorPerformance(ctx context.Context)

MonitorPerformance 监控性能指标

type ProtobufConfiguration

type ProtobufConfiguration struct {
	Enabled      bool
	Registry     *protoregistry.Types
	JSONOptions  protojson.MarshalOptions
	MessageTypes map[string]protoreflect.MessageType
}

ProtobufConfiguration protobuf配置结构

type ProtobufExample

type ProtobufExample struct {
	// contains filtered or unexported fields
}

ProtobufExample 演示如何使用增强的protobuf支持

func NewProtobufExample

func NewProtobufExample(proxy *GRPCProxy) *ProtobufExample

NewProtobufExample 创建protobuf示例

func (*ProtobufExample) ExampleAdvancedFeatures

func (e *ProtobufExample) ExampleAdvancedFeatures() error

ExampleAdvancedFeatures 高级功能示例

func (*ProtobufExample) ExampleBasicUsage

func (e *ProtobufExample) ExampleBasicUsage() error

ExampleBasicUsage 基本用法示例

func (*ProtobufExample) ExampleGRPCCall

func (e *ProtobufExample) ExampleGRPCCall(ctx context.Context) error

ExampleGRPCCall gRPC调用示例

func (*ProtobufExample) ExampleMessageConversion

func (e *ProtobufExample) ExampleMessageConversion() error

ExampleMessageConversion 消息转换示例

type ProtobufHealthCheck

type ProtobufHealthCheck struct {
	// contains filtered or unexported fields
}

ProtobufHealthCheck protobuf健康检查

func NewProtobufHealthCheck

func NewProtobufHealthCheck(proxy *GRPCProxy) *ProtobufHealthCheck

NewProtobufHealthCheck 创建protobuf健康检查

func (*ProtobufHealthCheck) Check

Check 执行protobuf相关的健康检查

type ProtobufHealthStatus

type ProtobufHealthStatus struct {
	IsHealthy       bool   `json:"is_healthy"`
	Enabled         bool   `json:"enabled"`
	RegisteredTypes int    `json:"registered_types"`
	Message         string `json:"message"`
}

ProtobufHealthStatus protobuf健康状态

type ProtobufMiddleware

type ProtobufMiddleware struct {
	// contains filtered or unexported fields
}

ProtobufMiddleware protobuf中间件示例

func NewProtobufMiddleware

func NewProtobufMiddleware(proxy *GRPCProxy) *ProtobufMiddleware

NewProtobufMiddleware 创建protobuf中间件

func (*ProtobufMiddleware) InterceptRequest

func (m *ProtobufMiddleware) InterceptRequest(ctx context.Context, request *GRPCRequest) (*GRPCRequest, error)

InterceptRequest 拦截请求并处理protobuf相关逻辑

type ProtobufUtils

type ProtobufUtils struct{}

ProtobufUtils protobuf工具函数集合

func NewProtobufUtils

func NewProtobufUtils() *ProtobufUtils

NewProtobufUtils 创建protobuf工具

func (*ProtobufUtils) GetProtobufFieldCount

func (u *ProtobufUtils) GetProtobufFieldCount(data []byte) int

GetProtobufFieldCount 估算protobuf消息中的字段数量

func (*ProtobufUtils) IsProtobufData

func (u *ProtobufUtils) IsProtobufData(data []byte) bool

IsProtobufData 检测数据是否为protobuf格式

type ResponseCache

type ResponseCache struct {
	// contains filtered or unexported fields
}

ResponseCache 响应缓存

func NewResponseCache

func NewResponseCache(logger *zap.Logger) *ResponseCache

NewResponseCache 创建响应缓存

func (*ResponseCache) Get

func (c *ResponseCache) Get(key string) ([]byte, bool)

Get 从缓存获取数据

func (*ResponseCache) Set

func (c *ResponseCache) Set(key string, data []byte, ttl time.Duration)

Set 设置缓存数据

type ResponseMapper

type ResponseMapper struct {
	Type     string            `json:"type"`     // 映射类型: merge, template
	Template string            `json:"template"` // 模板字符串
	Merge    map[string]string `json:"merge"`    // 合并配置
}

ResponseMapper 响应映射配置

type Route

type Route struct {
	Name        string            `json:"name"`        // 路由名称
	Path        string            `json:"path"`        // 路径匹配规则
	ServiceName string            `json:"serviceName"` // 目标服务名称
	Protocol    string            `json:"protocol"`    // 目标服务协议: http, grpc, etc.
	Methods     []string          `json:"methods"`     // 支持的HTTP方法
	StripPrefix bool              `json:"stripPrefix"` // 是否去除前缀
	Metadata    map[string]string `json:"metadata"`    // 元数据

	// API组合相关字段
	IsComposite    bool            `json:"isComposite"`    // 是否为组合路由
	CompositeSteps []CompositeStep `json:"compositeSteps"` // 组合步骤配置
	ResponseMapper ResponseMapper  `json:"responseMapper"` // 响应映射配置
}

Route 路由配置

type SecurityConfig

type SecurityConfig struct {
	EnableCORS          bool     `json:"enableCORS"`          // 是否启用CORS
	AllowedOrigins      []string `json:"allowedOrigins"`      // 允许的源
	EnableRateLimiting  bool     `json:"enableRateLimiting"`  // 是否启用限流
	EnableAuth          bool     `json:"enableAuth"`          // 是否启用认证
	APIKeys             []string `json:"apiKeys"`             // API密钥列表
	MaxRequestBodySize  int64    `json:"maxRequestBodySize"`  // 最大请求体大小
	EnableInputSanitize bool     `json:"enableInputSanitize"` // 是否启用输入清理
}

SecurityConfig 安全配置

type SecurityMiddleware

type SecurityMiddleware struct {
	// contains filtered or unexported fields
}

SecurityMiddleware 安全中间件配置

func NewSecurityMiddleware

func NewSecurityMiddleware(logger *zap.Logger) *SecurityMiddleware

NewSecurityMiddleware 创建安全中间件

func (*SecurityMiddleware) AuthMiddleware

func (s *SecurityMiddleware) AuthMiddleware(config *SecurityConfig) func(http.Handler) http.Handler

AuthMiddleware 认证中间件

func (*SecurityMiddleware) CORSMiddleware

func (s *SecurityMiddleware) CORSMiddleware(config *SecurityConfig) func(http.Handler) http.Handler

CORSMiddleware CORS中间件

func (*SecurityMiddleware) InputSanitizeMiddleware

func (s *SecurityMiddleware) InputSanitizeMiddleware(config *SecurityConfig) func(http.Handler) http.Handler

InputSanitizeMiddleware 输入清理中间件

func (*SecurityMiddleware) RequestSizeMiddleware

func (s *SecurityMiddleware) RequestSizeMiddleware(config *SecurityConfig) func(http.Handler) http.Handler

RequestSizeMiddleware 请求大小限制中间件

func (*SecurityMiddleware) SecurityHeadersMiddleware

func (s *SecurityMiddleware) SecurityHeadersMiddleware() func(http.Handler) http.Handler

SecurityHeadersMiddleware 安全头中间件

type TCPProxy

type TCPProxy struct {
	// contains filtered or unexported fields
}

TCPProxy TCP代理处理器(用于非HTTP协议)

func NewTCPProxy

func NewTCPProxy(logger *zap.Logger, discovery *discovery.Discovery) *TCPProxy

NewTCPProxy 创建新的TCP代理

func (*TCPProxy) Close

func (p *TCPProxy) Close() error

Close 关闭TCP代理(TCP代理没有需要关闭的连接池,所以返回nil)

func (*TCPProxy) ProxyTCPRequest

func (p *TCPProxy) ProxyTCPRequest(serviceName string, data []byte) ([]byte, error)

ProxyTCPRequest 代理TCP请求

type ValidationError

type ValidationError struct {
	Field   string `json:"field"`
	Message string `json:"message"`
}

ValidationError 验证错误

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL