gorp

package module
v0.1.4 Latest Latest
Warning

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

Go to latest
Published: Jun 2, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

Package gorp provides the root-package application startup surface for gorp framework. Exposes top-level aliases for runtime/app assembly and common startup options. Re-export runtime access types, callbacks, errors from framework/application.

Gorp 包提供 gorp 框架的根包层应用启动入口。 暴露 runtime/app 装配所需的顶层别名和常用启动选项。 从 framework/application 重导出 runtime 访问类型、回调、错误。

Eg:

gorp.Run(
    gorp.WithProviders(configprovider.NewProvider()),
    gorp.WithHTTPRoutes(registerRoutes),
)

HTTP is enabled by default. Use gorp.HTTP() only when you need HTTPServiceOptions. Use gorp.WithoutHTTP() to explicitly disable the HTTP mainline. Service name is read from config file (app.name) automatically.

HTTP 默认已启用。仅当需要传入 HTTPServiceOptions 时才调用 gorp.HTTP()。 使用 gorp.WithoutHTTP() 可显式关闭 HTTP 主线。 服务名自动从配置文件 app.name 读取。

Package gorp exposes the stable public entrypoints of the framework.

The root package stays intentionally thin:

  • application startup and mainline assembly entrypoints live here
  • a small set of high-frequency convenience helpers live here
  • default HTTP response helpers live here as fallback behavior
  • concrete implementations and advanced capabilities stay in framework/* and contrib/*

For business code, prefer the narrowest public surface that solves the task:

  • use package gorp for startup, common entry helpers, and default HTTP response fallback
  • use focused top-level helper packages such as cache/log/retry/jwt/dlock/validate for capability access
  • drop into framework/contract/* or provider-specific APIs only when lower-level control is really needed

Package gorp provides the root-package application startup surface for gorp framework. This file exposes aliases and helpers for integration capabilities. Provides short public path for message queue, distributed lock, and outbox.

Gorp 包提供 gorp 框架的根包层应用启动入口。 本文件暴露根包层的集成能力别名和 helper。 让业务代码通过简短公共路径获取常用 integration 能力。

Package gorp provides the root-package application startup surface for gorp framework. This file exposes HTTP response helpers built on framework responder chain. Gives business handlers short path for success and error response output.

Gorp 包提供 gorp 框架的根包层应用启动入口。 本文件暴露基于框架 responder 链的 HTTP 响应 helper。 为业务 handler 提供简短的成功/错误响应输出入口。

Eg:

func Ping(c gorp.Context) {
    gorp.Success(c, map[string]any{"pong": true})
}

Package gorp provides the root-package application startup surface for gorp framework. This file exposes security context helpers and shared security aliases. Keeps JWT subject and service-identity access convenient for handlers.

Gorp 包提供 gorp 框架的根包层应用启动入口。 本文件暴露根包层的安全上下文 helper 和共享安全别名。 让 handler 和 middleware 更方便地访问 JWT 主体与服务身份信息。

Package gorp provides the root-package application startup surface for gorp framework. This file exposes context helpers for container, validated body, request ID, trace ID. Keeps high-frequency support context accessors available from top-level API.

Gorp 包提供 gorp 框架的根包层应用启动入口。 本文件暴露根包层的 container、validated body、request ID、trace ID context helper。 让高频 support 上下文访问入口可以直接从顶层公共 API 使用。

Package gorp provides the root-package application startup surface for gorp framework. This file exposes transport contracts, middleware composition helpers, HTTP middleware presets. Re-exports stable transport surface without forcing callers into lower-level packages.

Gorp 包提供 gorp 框架的根包层应用启动入口。 本文件暴露根包层的 transport 契约、中间件组合 helper 和 HTTP 中间件预设入口。 在不强迫调用方下沉到更底层 framework 包的前提下重导出稳定 transport 能力。

Package gorp provides the root-package application startup surface for gorp framework. This file exposes the public version marker of the root package. Provides stable constant for build/version display for release tooling.

Gorp 包提供 gorp 框架的根包层应用启动入口。 本文件暴露根包层的公共版本标记。 为发布工具和业务代码提供稳定的构建/版本展示常量。

Index

Constants

View Source
const (
	// GovernanceModeMono keeps the runtime on the lightweight mono governance mainline.
	//
	// GovernanceModeMono 表示继续使用轻量、单体优先的默认治理主线。
	GovernanceModeMono = resiliencecontract.GovernanceModeMono
	// GovernanceModeMicro enables the default microservice governance mainline.
	//
	// GovernanceModeMicro 表示启用默认微服务治理主线。
	GovernanceModeMicro = resiliencecontract.GovernanceModeMicro
)
View Source
const (
	// HTTPModeContract uses gorp.Context abstraction.
	//
	// HTTPModeContract 使用 gorp.Context 契约抽象。
	HTTPModeContract = resiliencecontract.HTTPModeContract
	// HTTPModeGin uses native gin.Context directly.
	//
	// HTTPModeGin 使用原生 gin.Context。
	HTTPModeGin = resiliencecontract.HTTPModeGin
)
View Source
const DBRuntimeKey = data.DBRuntimeKey

DBRuntimeKey is the container binding key of the DB runtime capability.

DBRuntimeKey 是 DB runtime 能力的容器绑定键。

View Source
const Release = "dev"

Release is the current public root-package version marker. Release 是当前根包公开版本标记。

It defaults to "dev" in source builds and can be overridden at release time if needed. 源码构建时默认值为 "dev",发布时可按需覆盖。

Variables

View Source
var (
	// ErrNoServiceDeclared indicates that no runnable service has been declared.
	//
	// ErrNoServiceDeclared 表示未声明可运行服务。
	ErrNoServiceDeclared = application.ErrNoServiceDeclared
	// ErrHTTPRouteRegistrationFailed indicates that HTTP route registration failed.
	//
	// ErrHTTPRouteRegistrationFailed 表示 HTTP 路由注册失败。
	ErrHTTPRouteRegistrationFailed = application.ErrHTTPRouteRegistrationFailed
	// ErrHTTPRuntimeUnavailable indicates that the HTTP runtime is unavailable during route setup.
	//
	// ErrHTTPRuntimeUnavailable 表示在路由注册阶段缺少可用 HTTP runtime。
	ErrHTTPRuntimeUnavailable = application.ErrHTTPRuntimeUnavailable
	// ErrSetupFailed indicates that the setup callback failed.
	//
	// ErrSetupFailed 表示 setup 回调执行失败。
	ErrSetupFailed = application.ErrSetupFailed
	// ErrMigrateFailed indicates that the migrate callback failed.
	//
	// ErrMigrateFailed 表示 migrate 回调执行失败。
	ErrMigrateFailed = application.ErrMigrateFailed
	// ErrStartupCanceled indicates that startup was canceled before boot completed.
	//
	// ErrStartupCanceled 表示启动在完成前已被取消。
	ErrStartupCanceled = application.ErrStartupCanceled
	// ErrHTTPServiceRunFailed indicates that booting the default HTTP service failed.
	//
	// ErrHTTPServiceRunFailed 表示默认 HTTP 服务启动失败。
	ErrHTTPServiceRunFailed = application.ErrHTTPServiceRunFailed
	// ErrHTTPRuntimeBuildFailed indicates that building the HTTP runtime failed.
	//
	// ErrHTTPRuntimeBuildFailed 表示 HTTP runtime 构建失败。
	ErrHTTPRuntimeBuildFailed = application.ErrHTTPRuntimeBuildFailed
	// ErrGRPCServiceRunFailed indicates that booting the gRPC service failed.
	//
	// ErrGRPCServiceRunFailed 表示 gRPC 服务启动失败。
	ErrGRPCServiceRunFailed = application.ErrGRPCServiceRunFailed
	// ErrGRPCRuntimeBuildFailed indicates that building the gRPC runtime failed.
	//
	// ErrGRPCRuntimeBuildFailed 表示 gRPC runtime 构建失败。
	ErrGRPCRuntimeBuildFailed = application.ErrGRPCRuntimeBuildFailed
)

Functions

func AppendToClientContext

func AppendToClientContext(ctx context.Context, kv ...string) context.Context

AppendToClientContext appends key-value pairs to client transport metadata.

AppendToClientContext 向客户端 transport metadata 追加键值对。

func BadRequest

func BadRequest(c Context, message string)

BadRequest writes a bad-request HTTP response through the current responder chain.

BadRequest 通过当前 responder 链输出 bad request 响应。

func Error

func Error(c Context, err error)

Error writes an error HTTP response through the current responder chain.

Error 通过当前 responder 链输出错误 HTTP 响应。

func FromJWTClaimsContext

func FromJWTClaimsContext(ctx context.Context) (*securitycontract.JWTClaims, bool)

func FromRequestIDContext

func FromRequestIDContext(ctx context.Context) (string, bool)

func FromSubjectIDContext

func FromSubjectIDContext(ctx context.Context) (int64, bool)

func FromSubjectTypeContext

func FromSubjectTypeContext(ctx context.Context) (string, bool)

func FromTraceIDContext

func FromTraceIDContext(ctx context.Context) (string, bool)

func FromValidatedBodyContext

func FromValidatedBodyContext(ctx context.Context) (any, bool)

func GetGRPCRequestID

func GetGRPCRequestID(ctx context.Context) string

GetGRPCRequestID reads the request id from a gRPC context.

GetGRPCRequestID 从 gRPC context 读取 request id。

func GetGRPCTraceID

func GetGRPCTraceID(ctx context.Context) string

GetGRPCTraceID reads the trace id from a gRPC context.

GetGRPCTraceID 从 gRPC context 读取 trace id。

func InternalError

func InternalError(c Context, message string)

InternalError writes an internal-error HTTP response through the current responder chain.

InternalError 通过当前 responder 链输出内部错误响应。

func JWTSecretFromConfig added in v0.1.4

func JWTSecretFromConfig(cfg datacontract.Config) string

JWTSecretFromConfig 从容器配置中解析 JWT 密钥。 读取 `jwt.secret` 配置项。

JWTSecretFromConfig 统一从配置中解析 JWT secret。

func JWTService added in v0.1.4

func JWTService(ctx context.Context) (securitycontract.JWTService, error)

JWTService 从 ctx 或全局默认容器中获取 JWT 服务实例。 优先从 ctx 提取 Container,提取不到使用全局默认。

示例:

jwtSvc, err := gorp.JWTService(ctx)
token, err := jwtSvc.Sign(claims)

func MustJWTService added in v0.1.4

func MustJWTService(ctx context.Context) securitycontract.JWTService

MustJWTService 从 ctx 或全局默认容器获取 JWT 服务实例,失败时 panic。

MustJWTService 获取 JWT 服务,失败 panic。

func NewClientContext

func NewClientContext(ctx context.Context, md Metadata) context.Context

NewClientContext attaches metadata to a client-side context.

NewClientContext 向客户端 context 绑定 metadata。

func NewContainerContext

func NewContainerContext(ctx context.Context, c Container) context.Context

func NewJWTService added in v0.1.4

func NewJWTService(secret, issuer, audience string) securitycontract.JWTService

NewJWTService 从配置创建 JWT 服务实例。 不依赖 Container,直接传入 secret/issuer/audience 构造。

示例:

jwtSvc := gorp.NewJWTService("my-secret", "gorp-app", "api-users")

func NewServerContext

func NewServerContext(ctx context.Context, md Metadata) context.Context

NewServerContext attaches metadata to a server-side context.

NewServerContext 向服务端 context 绑定 metadata。

func Run

func Run(options ...Option) error

Run boots the default HTTP mainline with top-level gorp options. Service name is read from config file (app.name) automatically.

Run 使用顶层 gorp 选项启动默认 HTTP 主线。 服务名自动从配置文件 app.name 读取。

Example:

err := gorp.Run(
    gorp.HTTP(),
    gorp.WithHTTPRoutes(func(router gorp.Router, c gorp.Container) error {
        registerRoutes(router)
        return nil
    }),
)

func RunContext

func RunContext(ctx context.Context, options ...Option) error

RunContext boots the default HTTP mainline with an explicit context. Service name is read from config file (app.name) automatically.

RunContext 使用显式 context 启动默认 HTTP 主线。 服务名自动从配置文件 app.name 读取。

func Start deprecated

func Start(options ...Option) error

Start is an alias of Run.

Deprecated: Use Run instead. Start is kept for backward compatibility.

Start 是 Run 的同义入口。

Deprecated: 请使用 Run。Start 仅为向后兼容保留。

func Success

func Success(c Context, data any)

Success writes a successful HTTP response through the current responder chain.

Success 通过当前 responder 链输出成功 HTTP 响应。

func SuccessWithMessage

func SuccessWithMessage(c Context, message string, data any)

SuccessWithMessage writes a successful HTTP response with a custom message.

SuccessWithMessage 使用自定义 message 输出成功 HTTP 响应。

func SuccessWithStatus

func SuccessWithStatus(c Context, status int, data any)

SuccessWithStatus writes a successful HTTP response with a custom HTTP status.

SuccessWithStatus 使用自定义 HTTP status 输出成功响应。

func UseAdminAPIMiddleware

func UseAdminAPIMiddleware(router Router, base observabilitycontract.Logger, opts AdminMiddlewareOptions)

UseAdminAPIMiddleware applies the recommended admin API middleware preset to the router.

UseAdminAPIMiddleware 将推荐的管理 API 中间件预设装配到路由器。

func UseDefaultMiddleware

func UseDefaultMiddleware(router Router, base observabilitycontract.Logger)

UseDefaultMiddleware applies the default HTTP middleware baseline to the router.

UseDefaultMiddleware 将默认 HTTP 中间件基线装配到路由器。

func UseDefaultServiceGovernance

func UseDefaultServiceGovernance(router Router, base observabilitycontract.Logger, opts DefaultServiceGovernanceOptions)

UseDefaultServiceGovernance applies the default HTTP service governance preset to the router.

UseDefaultServiceGovernance 将默认 HTTP 服务治理预设装配到路由器。

func UseInternalAPIMiddleware

func UseInternalAPIMiddleware(router Router, base observabilitycontract.Logger, opts InternalMiddlewareOptions)

UseInternalAPIMiddleware applies the recommended internal API middleware preset to the router.

UseInternalAPIMiddleware 将推荐的内网 API 中间件预设装配到路由器。

func UseRecommendedAPIMiddleware

func UseRecommendedAPIMiddleware(router Router, base observabilitycontract.Logger, opts RecommendedMiddlewareOptions)

UseRecommendedAPIMiddleware applies the recommended public API middleware preset to the router.

UseRecommendedAPIMiddleware 将推荐的对外 API 中间件预设装配到路由器。

func WithServiceIdentity

func WithServiceIdentity(ctx context.Context, identity *ServiceIdentity) context.Context

Types

type AdminMiddlewareOptions

type AdminMiddlewareOptions = httpmiddleware.AdminMiddlewareOptions

AdminMiddlewareOptions is the top-level alias of the admin HTTP preset options.

AdminMiddlewareOptions 是管理 HTTP 预设选项的顶层别名。

func DefaultAdminMiddlewareOptions

func DefaultAdminMiddlewareOptions() AdminMiddlewareOptions

DefaultAdminMiddlewareOptions returns the default admin API middleware preset options.

DefaultAdminMiddlewareOptions 返回默认的管理 API 中间件预设选项。

type BodyDumpOptions

type BodyDumpOptions = httpmiddleware.BodyDumpOptions

BodyDumpOptions is the top-level alias of request/response capture middleware options.

BodyDumpOptions 是请求响应抓取中间件选项的顶层别名。

type Container

type Container = runtime.Container

Container is the top-level alias of the runtime container contract.

Container 是 runtime 容器契约的顶层别名。

func FromContainerContext

func FromContainerContext(ctx context.Context) (Container, bool)

type Context

type Context = transport.Context

Context is the top-level alias of the transport context contract.

Context 是 transport 层 Context 契约的顶层别名。

type DefaultServiceGovernanceOptions

type DefaultServiceGovernanceOptions = httpmiddleware.DefaultHTTPServiceGovernanceOptions

DefaultServiceGovernanceOptions is the top-level alias of the HTTP service governance preset options.

DefaultServiceGovernanceOptions 是 HTTP 服务治理预设选项的顶层别名。

func DefaultServiceGovernanceDefaults

func DefaultServiceGovernanceDefaults() DefaultServiceGovernanceOptions

DefaultServiceGovernanceDefaults returns the default HTTP service governance preset options.

DefaultServiceGovernanceDefaults 返回默认 HTTP 服务治理预设选项。

type DistributedLock

type DistributedLock = data.DistributedLock

DistributedLock is the top-level alias of the distributed lock contract. DistributedLock 是分布式锁契约的顶层别名。

func MakeDistributedLock

func MakeDistributedLock(c Container) (DistributedLock, error)

MakeDistributedLock returns the distributed lock capability from the container. MakeDistributedLock 从容器中获取分布式锁能力。

type ExchangeCapture

type ExchangeCapture = httpmiddleware.HTTPExchangeCapture

ExchangeCapture is the top-level alias of the request/response capture result.

ExchangeCapture 是请求响应抓取结果的顶层别名。

type GRPCConnFactory

type GRPCConnFactory = transport.GRPCConnFactory

GRPCConnFactory is the top-level alias of the proto-first gRPC connection factory.

GRPCConnFactory 是 proto-first gRPC 连接工厂的顶层别名。

func MakeGRPCConnFactory

func MakeGRPCConnFactory(c Container) (GRPCConnFactory, error)

MakeGRPCConnFactory returns the proto-first gRPC connection factory from the container.

MakeGRPCConnFactory 从容器中返回 proto-first gRPC 连接工厂。

type GRPCRuntime

type GRPCRuntime = application.GRPCRuntime

GRPCRuntime is the top-level alias of the application gRPC runtime.

GRPCRuntime 是 application gRPC runtime 的顶层别名。

type GRPCServerRegistrar

type GRPCServerRegistrar = transport.GRPCServerRegistrar

GRPCServerRegistrar is the top-level alias of the proto-first gRPC server registrar.

GRPCServerRegistrar 是 proto-first gRPC 服务注册器的顶层别名。

func MakeGRPCServerRegistrar

func MakeGRPCServerRegistrar(c Container) (GRPCServerRegistrar, error)

MakeGRPCServerRegistrar returns the proto-first gRPC server registrar from the container.

MakeGRPCServerRegistrar 从容器中返回 proto-first gRPC 服务注册器。

type GovernanceMode

type GovernanceMode = resiliencecontract.GovernanceMode

GovernanceMode is the top-level alias of the runtime governance mode.

GovernanceMode 是运行时治理模式的顶层别名。

type HTTPMode

type HTTPMode = resiliencecontract.HTTPMode

HTTPMode is the top-level alias of the HTTP handling abstraction mode.

HTTPMode 是 HTTP 处理抽象模式的顶层别名。

type HTTPRouteRegistrar

type HTTPRouteRegistrar = application.HTTPRouteRegistrar

HTTPRouteRegistrar is the top-level alias of the HTTP route registration callback contract.

HTTPRouteRegistrar 是 HTTP 路由注册回调契约的顶层别名。

type HTTPRuntime

type HTTPRuntime = application.HTTPRuntime

HTTPRuntime is the top-level alias of the application HTTP runtime.

HTTPRuntime 是 application HTTP runtime 的顶层别名。

func Build deprecated

func Build(options ...Option) (*HTTPRuntime, error)

Build is an alias of BuildHTTPRuntime.

Deprecated: Use BuildHTTPRuntime instead. Build is kept for backward compatibility.

Build 是 BuildHTTPRuntime 的同义入口。

Deprecated: 请使用 BuildHTTPRuntime。Build 仅为向后兼容保留。

func BuildHTTPRuntime

func BuildHTTPRuntime(options ...Option) (*HTTPRuntime, error)

BuildHTTPRuntime builds the HTTP runtime without starting listeners. Service name is read from config file (app.name) automatically.

BuildHTTPRuntime 构建 HTTP runtime,但不启动监听。 服务名自动从配置文件 app.name 读取。

type HTTPServiceOptions

type HTTPServiceOptions = application.HTTPServiceOptions

HTTPServiceOptions is the top-level alias of application HTTP service options.

HTTPServiceOptions 是 application HTTP 服务选项的顶层别名。

type Handler

type Handler = transport.Handler

Handler is the top-level alias of the transport handler contract.

Handler 是 transport 层 Handler 契约的顶层别名。

type InternalMiddlewareOptions

type InternalMiddlewareOptions = httpmiddleware.InternalMiddlewareOptions

InternalMiddlewareOptions is the top-level alias of the internal HTTP preset options.

InternalMiddlewareOptions 是内网 HTTP 预设选项的顶层别名。

func DefaultInternalMiddlewareOptions

func DefaultInternalMiddlewareOptions() InternalMiddlewareOptions

DefaultInternalMiddlewareOptions returns the default internal API middleware preset options.

DefaultInternalMiddlewareOptions 返回默认的内网 API 中间件预设选项。

type JWTClaims added in v0.1.4

type JWTClaims = securitycontract.JWTClaims

JWTClaims 是共享的业务 JWT claims 模型的顶层别名。 业务 handler 通过 gorp.ClaimsFromContext(c) 获取 claims 后可直接使用此类型。

func ClaimsFromContext added in v0.1.4

func ClaimsFromContext(c Context) (*JWTClaims, bool)

ClaimsFromContext 从 transport.Context 提取 JWT claims。 优先从 c.Get() 读取(中间件主路径),回退到 c.Context() 标准上下文读取。 这是业务 handler 提取 claims 的推荐方式。

示例:

claims, ok := gorp.ClaimsFromContext(c)

type Message

type Message = integration.Message

Message is the top-level alias of the integration message contract. Message 是集成消息契约的顶层别名。

type MessagePublisher

type MessagePublisher = integration.MessagePublisher

MessagePublisher is the top-level alias of the message publisher contract. MessagePublisher 是消息发布契约的顶层别名。

func MakeMessagePublisher

func MakeMessagePublisher(c Container) (MessagePublisher, error)

MakeMessagePublisher returns the message publishing capability from the container. MakeMessagePublisher 从容器中获取消息发布能力。

type MessageSubscriber

type MessageSubscriber = integration.MessageSubscriber

MessageSubscriber is the top-level alias of the message subscriber contract. MessageSubscriber 是消息订阅契约的顶层别名。

func MakeMessageSubscriber

func MakeMessageSubscriber(c Container) (MessageSubscriber, error)

MakeMessageSubscriber returns the message subscription capability from the container. MakeMessageSubscriber 从容器中获取消息订阅能力。

type Metadata

type Metadata = transport.Metadata

Metadata is the top-level alias of the transport metadata contract.

Metadata 是 transport 层 metadata 契约的顶层别名。

func FromClientContext

func FromClientContext(ctx context.Context) (Metadata, bool)

FromClientContext reads transport metadata from a client-side context.

FromClientContext 从客户端 context 读取 transport metadata。

func FromServerContext

func FromServerContext(ctx context.Context) (Metadata, bool)

FromServerContext reads transport metadata from a server-side context.

FromServerContext 从服务端 context 读取 transport metadata。

func NewMetadata

func NewMetadata() Metadata

NewMetadata creates a transport metadata container.

NewMetadata 创建一个 transport metadata 容器。

type Middleware

type Middleware = transport.Middleware

Middleware is the top-level alias of the transport middleware contract.

Middleware 是 transport 层 Middleware 契约的顶层别名。

func AdaptMiddleware

func AdaptMiddleware(fn MiddlewareFunc) Middleware

AdaptMiddleware adapts a business-friendly middleware callback to Middleware.

AdaptMiddleware 将业务友好的回调签名适配为 Middleware。

Example:

func AccessLog() gorp.Middleware {
    return gorp.AdaptMiddleware(func(ctx gorp.Context, next gorp.Handler) {
        if next != nil {
            next(ctx)
        }
    })
}

func AdminAPIMiddleware

func AdminAPIMiddleware(base observabilitycontract.Logger, opts AdminMiddlewareOptions) Middleware

AdminAPIMiddleware returns the recommended admin API middleware preset.

AdminAPIMiddleware 返回推荐的管理 API 中间件预设。

func AdminAPIMiddlewareSet

func AdminAPIMiddlewareSet(base observabilitycontract.Logger, opts AdminMiddlewareOptions) []Middleware

AdminAPIMiddlewareSet returns the recommended admin API middleware preset as an ordered slice.

AdminAPIMiddlewareSet 以有序切片形式返回推荐的管理 API 中间件预设。

func BodyDump

func BodyDump(opts BodyDumpOptions) Middleware

BodyDump returns the request/response capture middleware from the mainline HTTP middleware package.

BodyDump 返回主线 HTTP 中间件中的请求响应抓取中间件。

func Chain

func Chain(middleware ...Middleware) Middleware

Chain combines multiple middlewares into one middleware.

Chain 将多个中间件组合成一个中间件。

Example:

apiMiddleware := gorp.Chain(
    gorp.RequestIdentity(),
    gorp.LoggingMiddleware(logger),
    gorp.RecoveryMiddleware(),
)

router.Use(apiMiddleware)

func DefaultMiddleware

func DefaultMiddleware(base observabilitycontract.Logger) Middleware

DefaultMiddleware returns the stable default HTTP middleware baseline.

DefaultMiddleware 返回稳定的默认 HTTP 中间件基线。

func DefaultMiddlewareSet

func DefaultMiddlewareSet(base observabilitycontract.Logger) []Middleware

DefaultMiddlewareSet returns the stable default HTTP middleware baseline as an ordered slice.

DefaultMiddlewareSet 以有序切片形式返回稳定的默认 HTTP 中间件基线。

func DefaultServiceGovernancePreset

func DefaultServiceGovernancePreset(base observabilitycontract.Logger, opts DefaultServiceGovernanceOptions) Middleware

DefaultServiceGovernancePreset returns the default HTTP service governance middleware preset.

DefaultServiceGovernancePreset 返回默认 HTTP 服务治理中间件预设。

func DefaultServiceGovernanceSet

func DefaultServiceGovernanceSet(base observabilitycontract.Logger, opts DefaultServiceGovernanceOptions) []Middleware

DefaultServiceGovernanceSet returns the default HTTP service governance preset as an ordered slice.

DefaultServiceGovernanceSet 以有序切片形式返回默认 HTTP 服务治理预设。

func InternalAPIMiddleware

func InternalAPIMiddleware(base observabilitycontract.Logger, opts InternalMiddlewareOptions) Middleware

InternalAPIMiddleware returns the recommended internal API middleware preset.

InternalAPIMiddleware 返回推荐的内网 API 中间件预设。

func InternalAPIMiddlewareSet

func InternalAPIMiddlewareSet(base observabilitycontract.Logger, opts InternalMiddlewareOptions) []Middleware

InternalAPIMiddlewareSet returns the recommended internal API middleware preset as an ordered slice.

InternalAPIMiddlewareSet 以有序切片形式返回推荐的内网 API 中间件预设。

func RecommendedAPIMiddleware

func RecommendedAPIMiddleware(base observabilitycontract.Logger, opts RecommendedMiddlewareOptions) Middleware

RecommendedAPIMiddleware returns the recommended public API middleware preset.

RecommendedAPIMiddleware 返回推荐的对外 API 中间件预设。

func RecommendedAPIMiddlewareSet

func RecommendedAPIMiddlewareSet(base observabilitycontract.Logger, opts RecommendedMiddlewareOptions) []Middleware

RecommendedAPIMiddlewareSet returns the recommended public API middleware preset as an ordered slice.

RecommendedAPIMiddlewareSet 以有序切片形式返回推荐的对外 API 中间件预设。

func Tenant

func Tenant(opts TenantOptions) Middleware

Tenant returns the tenant middleware from the mainline HTTP middleware package.

Tenant 返回主线 HTTP 中间件中的租户中间件。

type MiddlewareFunc

type MiddlewareFunc func(ctx Context, next Handler)

MiddlewareFunc is the business-friendly helper signature used by Middleware.

MiddlewareFunc 是 Middleware 使用的业务友好辅助签名。

type MigrateFunc

type MigrateFunc = application.MigrateFunc

MigrateFunc is the top-level alias of the application migrate callback contract.

MigrateFunc 是 application migrate 回调契约的顶层别名。

type Option

type Option = application.Option

Option is the top-level alias of the application startup option contract.

Option 是 application 启动选项契约的顶层别名。

func GRPC

func GRPC() Option

GRPC declares that the gRPC service should be started alongside the HTTP mainline. This enables the gRPC server in the HTTPServiceRuntime, allowing users to register proto services via rt.GRPCServer in the setup callback.

GRPC 声明在 HTTP 主线之外同时启动 gRPC 服务。 这会在 HTTPServiceRuntime 中启用 gRPC 服务器,允许用户在 setup 回调中 通过 rt.GRPCServer 注册 proto 服务。

Example:

gorp.Run("user-service",
    gorp.HTTP(),
    gorp.GRPC(),
    gorp.WithMicroMode(),
    gorp.WithSetup(func(rt *gorp.HTTPRuntime) error {
        pb.RegisterUserServiceServer(rt.GRPCServer, userService)
        return nil
    }),
)

func HTTP

func HTTP(opts ...HTTPServiceOptions) Option

HTTP declares that the default HTTP mainline should be used. HTTP declares HTTP service options. The HTTP mainline is enabled by default, so calling HTTP() without arguments is unnecessary. Use HTTP() only when you need to pass HTTPServiceOptions. Use WithoutHTTP() to explicitly disable HTTP.

HTTP 声明 HTTP 服务选项。HTTP 主线默认已启用,无参调用 HTTP() 是冗余的。 仅当需要传入 HTTPServiceOptions 时才调用。使用 WithoutHTTP() 可显式关闭 HTTP 主线。

func Module deprecated

func Module(providers ...ServiceProvider) Option

Module declares providers for a single module.

Deprecated: Use WithProviders instead. Module is kept for backward compatibility.

Module 声明单个模块的 providers。

Deprecated: 请使用 WithProviders。Module 仅为向后兼容保留。

func Modules

func Modules(groups ...[]ServiceProvider) Option

Modules declares providers for a group of modules.

Modules 声明一组模块的 providers。

func WithContractHTTPMode

func WithContractHTTPMode() Option

WithContractHTTPMode selects the gorp.Context contract abstraction.

WithContractHTTPMode 选择 gorp.Context 契约抽象。

func WithGinHTTPMode

func WithGinHTTPMode() Option

WithGinHTTPMode selects the native gin.Context mode.

WithGinHTTPMode 选择原生 gin.Context 模式。

func WithGovernanceDisabled

func WithGovernanceDisabled(names ...string) Option

WithGovernanceDisabled explicitly disables one or more default governance capabilities.

WithGovernanceDisabled 显式关闭一个或多个默认治理能力。

func WithGovernanceEnabled

func WithGovernanceEnabled(names ...string) Option

WithGovernanceEnabled explicitly enables one or more governance capabilities that are off by default. This is the symmetric counterpart of WithGovernanceDisabled. When the same feature appears in both enable and disable, disable takes precedence.

WithGovernanceEnabled 显式开启一个或多个默认关闭的治理能力。 这是 WithGovernanceDisabled 的对称入口。 当同一 feature 同时出现在 enable 和 disable 中时,disable 生效。

func WithGovernanceMode

func WithGovernanceMode(mode GovernanceMode) Option

WithGovernanceMode declares the runtime governance mode explicitly.

WithGovernanceMode 显式声明运行时治理模式。

func WithGovernanceProvider

func WithGovernanceProvider(name, backend string) Option

WithGovernanceProvider explicitly overrides one governance provider backend.

WithGovernanceProvider 显式覆盖一个治理 provider backend。

func WithHTTPMode

func WithHTTPMode(mode HTTPMode) Option

WithHTTPMode declares the HTTP handling mode explicitly.

WithHTTPMode 显式声明 HTTP 处理抽象模式。

func WithHTTPRoutes

func WithHTTPRoutes(register HTTPRouteRegistrar) Option

WithHTTPRoutes declares the default HTTP route registration callback.

WithHTTPRoutes 声明默认 HTTP 路由注册回调。

func WithMicroGovernance

func WithMicroGovernance() Option

WithMicroGovernance selects microservice governance and HTTP contract mode.

WithMicroGovernance 选择微服务治理 + HTTP 契约模式。

func WithMicroMode

func WithMicroMode() Option

WithMicroMode selects the microservice governance mainline.

WithMicroMode 选择微服务治理主线。

func WithMigrate

func WithMigrate(fn MigrateFunc) Option

WithMigrate declares a migrate callback.

WithMigrate 声明 migrate 回调。

func WithModule deprecated

func WithModule(providers ...ServiceProvider) Option

WithModule is the explicit named alias of Module.

Deprecated: Use WithProviders instead. WithModule is kept for backward compatibility.

WithModule 是 Module 的显式命名入口。

Deprecated: 请使用 WithProviders。WithModule 仅为向后兼容保留。

func WithMonoGovernance

func WithMonoGovernance() Option

WithMonoGovernance selects mono governance (HTTP mode left to default or explicit).

WithMonoGovernance 选择单体治理(HTTP 模式由默认值或显式参数决定)。

func WithMonoMode

func WithMonoMode() Option

WithMonoMode selects the mono governance mainline.

WithMonoMode 选择单体治理主线。

func WithProviders

func WithProviders(providers ...ServiceProvider) Option

WithProviders appends provider declarations to the startup options.

WithProviders 向启动选项追加 provider 声明。

func WithSetup

func WithSetup(fn SetupFunc) Option

WithSetup declares a setup callback.

WithSetup 声明 setup 回调。

func WithoutHTTP

func WithoutHTTP() Option

WithoutHTTP explicitly disables the default HTTP declaration.

WithoutHTTP 显式关闭默认 HTTP 声明。

type RecommendedMiddlewareOptions

type RecommendedMiddlewareOptions = httpmiddleware.RecommendedMiddlewareOptions

RecommendedMiddlewareOptions is the top-level alias of the recommended HTTP preset options.

RecommendedMiddlewareOptions 是推荐 HTTP 预设选项的顶层别名。

func DefaultRecommendedMiddlewareOptions

func DefaultRecommendedMiddlewareOptions() RecommendedMiddlewareOptions

DefaultRecommendedMiddlewareOptions returns the default public API middleware preset options.

DefaultRecommendedMiddlewareOptions 返回默认的对外 API 中间件预设选项。

type Router

type Router = transport.Router

Router is the top-level alias of the transport router contract.

Router 是 transport 层 Router 契约的顶层别名。

type ServiceIdentity

type ServiceIdentity = securitycontract.ServiceIdentity

func FromServiceIdentity

func FromServiceIdentity(ctx context.Context) (*ServiceIdentity, bool)

type ServiceProvider

type ServiceProvider = runtime.ServiceProvider

ServiceProvider is the top-level alias of the runtime service provider contract.

ServiceProvider 是 runtime service provider 契约的顶层别名。

type SetupFunc

type SetupFunc = application.SetupFunc

SetupFunc is the top-level alias of the application setup callback contract.

SetupFunc 是 application setup 回调契约的顶层别名。

type TenantOptions

type TenantOptions = httpmiddleware.TenantOptions

TenantOptions is the top-level alias of tenant middleware options.

TenantOptions 是租户中间件选项的顶层别名。

func DefaultTenantOptions

func DefaultTenantOptions() TenantOptions

DefaultTenantOptions returns the default tenant middleware options.

DefaultTenantOptions 返回默认租户中间件选项。

Directories

Path Synopsis
cmd
gorp module
contrib
messagequeue
Package messagequeue provides shared metrics for MQ implementations.
Package messagequeue provides shared metrics for MQ implementations.
dlock/redis module
dtm/dtmsdk module
registry/etcd module
tracing/otel module
application
Package application provides application startup entrypoints for gorp framework.
Package application provides application startup entrypoints for gorp framework.
bootstrap
Package bootstrap provides framework bootstrap and assembly helpers for gorp.
Package bootstrap provides framework bootstrap and assembly helpers for gorp.
container
Package container provides runtime dependency injection container for gorp framework.
Package container provides runtime dependency injection container for gorp framework.
contract/data
Application scenarios: - Define the cache contract used by business services and framework providers.
Application scenarios: - Define the cache contract used by business services and framework providers.
contract/discovery
Application scenarios: - Define the service-instance selection contract used by discovery-aware RPC clients.
Application scenarios: - Define the service-instance selection contract used by discovery-aware RPC clients.
contract/integration
Application scenarios: - Define the distributed transaction contract used by business orchestration flows.
Application scenarios: - Define the distributed transaction contract used by business orchestration flows.
contract/observability
Application scenarios: - Define health check contracts for services and their dependencies.
Application scenarios: - Define health check contracts for services and their dependencies.
contract/resilience
Application scenarios: - Define the shared governance-mode and policy-provider contracts used by bootstrap and runtime assembly.
Application scenarios: - Define the shared governance-mode and policy-provider contracts used by bootstrap and runtime assembly.
contract/runtime
Application scenarios: - Define minimal business-facing runtime contracts shared across framework layers.
Application scenarios: - Define minimal business-facing runtime contracts shared across framework layers.
contract/security
Application scenarios: - Define the business-facing JWT authentication contract used by handlers and services.
Application scenarios: - Define the business-facing JWT authentication contract used by handlers and services.
contract/support
Application scenarios: - Attach the runtime container onto request-scoped or task-scoped contexts.
Application scenarios: - Attach the runtime container onto request-scoped or task-scoped contexts.
contract/transport
Application scenarios: - Define the framework-agnostic HTTP request context contract.
Application scenarios: - Define the framework-agnostic HTTP request context contract.
deploy
Package deploy provides deployment utilities for gorp framework.
Package deploy provides deployment utilities for gorp framework.
goroutine
Package goroutine provides goroutine safety utilities for gorp framework.
Package goroutine provides goroutine safety utilities for gorp framework.
grpc/interceptor
Application scenarios: - Provide one provider-neutral home for the framework's gRPC governance interceptor presets.
Application scenarios: - Provide one provider-neutral home for the framework's gRPC governance interceptor presets.
http/middleware
Application scenarios: - Record operator, resource, action, and outcome for business-sensitive endpoints.
Application scenarios: - Record operator, resource, action, and outcome for business-sensitive endpoints.
httpx
Package httpx provides HTTP utilities for gorp framework.
Package httpx provides HTTP utilities for gorp framework.
lifecycle
Package lifecycle provides service lifecycle management for gorp framework.
Package lifecycle provides service lifecycle management for gorp framework.
log
Package log provides lightweight logging utilities for gorp framework.
Package log provides lightweight logging utilities for gorp framework.
provider/app
Package app provides application root-path capability for gorp framework.
Package app provides application root-path capability for gorp framework.
provider/auth/jwt
Package jwt provides Gin HTTP middleware for JWT authentication.
Package jwt provides Gin HTTP middleware for JWT authentication.
provider/cache
Package cache provides in-memory cache implementation.
Package cache provides in-memory cache implementation.
provider/config
Package config provides environment normalization utilities for gorp framework.
Package config provides environment normalization utilities for gorp framework.
provider/configsource/local
Package local provides local file config source implementation for gorp framework.
Package local provides local file config source implementation for gorp framework.
provider/configsource/noop
Package noop provides a no-op config source for monolith scenarios.
Package noop provides a no-op config source for monolith scenarios.
provider/cron
Package cron provides cron scheduling service for gorp framework.
Package cron provides cron scheduling service for gorp framework.
provider/discovery/noop
Package noop provides a no-op service discovery registry for monolith scenarios.
Package noop provides a no-op service discovery registry for monolith scenarios.
provider/dlock/noop
Package noop provides a no-op distributed lock for monolith scenarios.
Package noop provides a no-op distributed lock for monolith scenarios.
provider/dtm/noop
Package noop provides a no-op DTM distributed transaction client for monolith scenarios.
Package noop provides a no-op DTM distributed transaction client for monolith scenarios.
provider/error_reporter
Package error_reporter provides error reporting service for gorp framework.
Package error_reporter provides error reporting service for gorp framework.
provider/errors/std
Package std provides standard error handling implementation for gorp framework.
Package std provides standard error handling implementation for gorp framework.
provider/event
Package event provides local in-memory event bus implementation for gorp framework.
Package event provides local in-memory event bus implementation for gorp framework.
provider/gin
Package gin provides Gin-based HTTP server implementation for gorp framework.
Package gin provides Gin-based HTTP server implementation for gorp framework.
provider/grpc
Package grpc provides gRPC interceptors for gorp framework.
Package grpc provides gRPC interceptors for gorp framework.
provider/health
Package health provides dependency health checkers for common components.
Package health provides dependency health checkers for common components.
provider/host
Package host provides service adapters for wrapping HTTP, Cron, and GRPC servers.
Package host provides service adapters for wrapping HTTP, Cron, and GRPC servers.
provider/loadshedding
Package loadshedding 提供过载保护(LoadShedding)实现。
Package loadshedding 提供过载保护(LoadShedding)实现。
provider/loadshedding/bbr
Package bbr 提供 BBR 自适应过载保护实现。
Package bbr 提供 BBR 自适应过载保护实现。
provider/loadshedding/noop
Package noop 提供 LoadShedding 的空实现。
Package noop 提供 LoadShedding 的空实现。
provider/log
Package log provides zap-based logging service for gorp framework.
Package log provides zap-based logging service for gorp framework.
provider/messagequeue/noop
Package noop provides a no-op message queue for monolith scenarios.
Package noop provides a no-op message queue for monolith scenarios.
provider/metadata
Package metadata provides metadata propagation service for gorp framework.
Package metadata provides metadata propagation service for gorp framework.
provider/metadata/middleware
Package middleware provides gRPC metadata propagation middleware.
Package middleware provides gRPC metadata propagation middleware.
provider/metadata/noop
Package noop provides no-op metadata implementation for monolith scenarios.
Package noop provides no-op metadata implementation for monolith scenarios.
provider/metadata/propagator
Package propagator provides metadata propagation implementation for gorp framework.
Package propagator provides metadata propagation implementation for gorp framework.
provider/observability
Package observability provides observability service implementation for gorp framework.
Package observability provides observability service implementation for gorp framework.
provider/orm/ent
Package ent provides Ent ORM integration for gorp framework.
Package ent provides Ent ORM integration for gorp framework.
provider/orm/gorm
Package gorm provides a custom GORM logger implementation.
Package gorm provides a custom GORM logger implementation.
provider/orm/inspect
Package inspect provides database schema inspection service.
Package inspect provides database schema inspection service.
provider/orm/runtime
Package runtime provides ORM backend abstraction and unified runtime services.
Package runtime provides ORM backend abstraction and unified runtime services.
provider/orm/sqlx
Package sqlx provides SQLX ORM integration for gorp framework.
Package sqlx provides SQLX ORM integration for gorp framework.
provider/outbox
Package outbox provides in-memory outbox pattern implementation for gorp framework.
Package outbox provides in-memory outbox pattern implementation for gorp framework.
provider/proto
Package proto provides proto generator implementation.
Package proto provides proto generator implementation.
provider/ratelimiter
Package ratelimiter provides rate limiting capability for gorp framework.
Package ratelimiter provides rate limiting capability for gorp framework.
provider/redis
Package redis provides Redis service for gorp framework.
Package redis provides Redis service for gorp framework.
provider/retry
Package retry provides retry service for gorp framework.
Package retry provides retry service for gorp framework.
provider/retry/noop
Application scenarios: - Provide the monolith-friendly no-op retry capability.
Application scenarios: - Provide the monolith-friendly no-op retry capability.
provider/rpc/grpc
Package grpc provides the gRPC-based RPC client for the gorp framework.
Package grpc provides the gRPC-based RPC client for the gorp framework.
provider/rpc/http
Package http provides HTTP RPC client for gorp framework.
Package http provides HTTP RPC client for gorp framework.
provider/rpc/noop
Package noop provides a no-op RPC client/server for monolith scenarios.
Package noop provides a no-op RPC client/server for monolith scenarios.
provider/selector/noop
Package noop provides a no-op load balancing selector for monolith scenarios.
Package noop provides a no-op load balancing selector for monolith scenarios.
provider/selector/p2c
Package p2c provides Power of Two Choices load balancing selector.
Package p2c provides Power of Two Choices load balancing selector.
provider/selector/random
Package random provides random load balancing selector for service discovery.
Package random provides random load balancing selector for service discovery.
provider/selector/wrr
Package wrr provides weighted round-robin load balancing selector.
Package wrr provides weighted round-robin load balancing selector.
provider/serviceauth/noop
Package noop provides a no-op service authenticator for monolith scenarios.
Package noop provides a no-op service authenticator for monolith scenarios.
provider/ssh
Package ssh provides SSH service for gorp framework.
Package ssh provides SSH service for gorp framework.
provider/tracing/middleware
Package middleware provides gRPC tracing middleware for gorp framework.
Package middleware provides gRPC tracing middleware for gorp framework.
provider/tracing/noop
Package noop provides a no-op tracing implementation for monolith scenarios.
Package noop provides a no-op tracing implementation for monolith scenarios.
provider/validate
Package validate provides a unified validation service using go-playground/validator.
Package validate provides a unified validation service using go-playground/validator.
provider/validate/noop
Package noop provides a no-op validator implementation for monolith scenarios.
Package noop provides a no-op validator implementation for monolith scenarios.
provider/websocket
Package websocket provides WebSocket capability provider for gorp framework.
Package websocket provides WebSocket capability provider for gorp framework.
provider/websocket/noop
Package noop provides a no-op WebSocket service implementation for gorp.
Package noop provides a no-op WebSocket service implementation for gorp.
rpc/governance
Application scenarios: - Provide a shared outbound RPC governance chain model used by HTTP and gRPC clients.
Application scenarios: - Provide a shared outbound RPC governance chain model used by HTTP and gRPC clients.
testing
Package testing provides testing utilities for gorp framework.
Package testing provides testing utilities for gorp framework.
Application scenarios: - Expose the framework logging capability through a short top-level package.
Application scenarios: - Expose the framework logging capability through a short top-level package.
Package retry provides a thin facade for the framework's retry capability.
Package retry provides a thin facade for the framework's retry capability.
test
integration/mock_backend command
Package main provides mock gRPC backend server implementation.
Package main provides mock gRPC backend server implementation.
integration/pb
Package pb provides test protobuf definitions for integration tests.
Package pb provides test protobuf definitions for integration tests.
Application scenarios: - Expose the unified validation capability through a top-level convenience package.
Application scenarios: - Expose the unified validation capability through a top-level convenience package.

Jump to

Keyboard shortcuts

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