standard

package
v1.4.3 Latest Latest
Warning

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

Go to latest
Published: Sep 22, 2026 License: Apache-2.0 Imports: 63 Imported by: 1

Documentation

Index

Constants

View Source
const (
	TraceIDKey        = "trace-id"
	SpanIDKey         = "span-id"
	JWTKey            = "jwt"
	DepthKey          = "x-depth"
	ClientIPKey       = "client-ip"
	ContentTypeKey    = "content-type"
	UserAgentKey      = "user-agent"
	AcceptLanguageKey = "accept-language"
)

Variables

View Source
var (
	// ErrInternal 表示未向调用方暴露内部实现细节的服务端错误。
	ErrInternal = NewError(codes.Internal, "internal server error")
	// ErrInvalidParam 表示请求参数不合法。
	ErrInvalidParam = NewError(codes.InvalidArgument, "invalid parameter")
	// ErrUnauthenticated 表示调用方尚未通过身份认证。
	ErrUnauthenticated = NewError(codes.Unauthenticated, "unauthenticated")
	// ErrNotFound 表示请求的资源不存在。
	ErrNotFound = NewError(codes.NotFound, "resource not found")
	// ErrPermissionDenied 表示调用方无权执行当前操作。
	ErrPermissionDenied = NewError(codes.PermissionDenied, "permission denied")
	// ErrAlreadyExists 表示待创建的资源已经存在。
	ErrAlreadyExists = NewError(codes.AlreadyExists, "resource already exists")
	// ErrResourceExhausted 表示请求超过服务允许的资源限制。
	ErrResourceExhausted = NewError(codes.ResourceExhausted, "resource exhausted")
	// ErrFailedPrecondition 表示当前系统状态不满足操作前置条件。
	ErrFailedPrecondition = NewError(codes.FailedPrecondition, "failed precondition")
	// ErrAborted 表示操作因并发冲突等原因被中止。
	ErrAborted = NewError(codes.Aborted, "operation aborted")
	// ErrUnavailable 表示服务暂时不可用。
	ErrUnavailable = NewError(codes.Unavailable, "service unavailable")
)

Functions

func NewClient

func NewClient(target string, opts ...ClientOption) (*grpc.ClientConn, error)

NewClient 创建由 lifex 管理的标准 gRPC ClientConn,默认使用明文连接。

func NewContext

func NewContext(ctx context.Context, kvs ...any) context.Context

NewContext 在保留已有参数的基础上创建新的请求上下文。

func SpanID

func SpanID(ctx context.Context) string

SpanID 返回标准中间件写入 context 的当前服务内单次请求处理标识。

func TraceID

func TraceID(ctx context.Context) string

TraceID 返回标准中间件写入 context 的链路追踪标识,跨服务透传。

Types

type AuditFunc added in v1.4.3

type AuditFunc func(context.Context, AuditInvocation) error

AuditFunc 将调用结果交给业务层记录。

type AuditInvocation added in v1.4.3

type AuditInvocation struct {
	Method   string
	Kind     string
	Request  any
	Response any
	Err      error
	Duration time.Duration
}

AuditInvocation 是一次需要审计的 RPC 调用,请求和响应已按字段选项脱敏。

type ClientOption

type ClientOption func(*clientConfig) error

ClientOption 配置标准 gRPC ClientConn。

func WithClientDialOptions

func WithClientDialOptions(opts ...grpc.DialOption) ClientOption

func WithClientLogger

func WithClientLogger(logger grpclogging.Logger) ClientOption

func WithClientRootCertificate

func WithClientRootCertificate(certFile string) ClientOption

func WithClientRootCertificatePEM

func WithClientRootCertificatePEM(certPEM []byte) ClientOption

func WithClientServerName

func WithClientServerName(serverName string) ClientOption

func WithClientStreamInterceptors

func WithClientStreamInterceptors(interceptors ...grpc.StreamClientInterceptor) ClientOption

func WithClientTLSConfig

func WithClientTLSConfig(tlsConfig *tls.Config) ClientOption

WithClientTLSConfig 使用自定义 TLS 配置连接 gRPC Server。

func WithClientUnaryInterceptors

func WithClientUnaryInterceptors(interceptors ...grpc.UnaryClientInterceptor) ClientOption

type Context

type Context struct {
	context.Context
	// contains filtered or unexported fields
}

Context 提供标准中间件写入的请求级参数,以及额外 HTTP Handler 的请求和响应能力。

func FromContext

func FromContext(ctx context.Context) *Context

FromContext 返回请求上下文中的扩展参数视图。

func NewHTTPContext

func NewHTTPContext(request *http.Request, response http.ResponseWriter, pathParams map[string]string) *Context

NewHTTPContext 创建包含原始 HTTP 请求、响应和路径参数的 Context,主要用于测试 Handler。

func (*Context) AcceptLanguage

func (c *Context) AcceptLanguage() string

AcceptLanguage 返回请求携带的原始语言偏好。

func (*Context) Blob

func (c *Context) Blob(statusCode int, contentType string, data []byte) error

Blob 以指定 Content-Type 写入二进制响应。

func (*Context) ClientIP

func (c *Context) ClientIP() string

func (*Context) ContentType

func (c *Context) ContentType() string

func (*Context) Depth

func (c *Context) Depth() int

func (*Context) FormFile

func (c *Context) FormFile(name string) (*multipart.FileHeader, error)

FormFile 返回 multipart 表单中的第一个文件。

func (*Context) FormValue

func (c *Context) FormValue(name string) string

FormValue 返回表单字段的第一个值。

func (*Context) Get

func (c *Context) Get(key any) any

func (*Context) Header

func (c *Context) Header(name string) string

Header 返回请求头的第一个值。

func (*Context) JSON

func (c *Context) JSON(statusCode int, value any) error

JSON 以 JSON 格式写入响应。

func (*Context) JWT

func (c *Context) JWT() jwt.MapClaims

JWT 返回鉴权中间件验证后的 Claims 副本。

func (*Context) JWTClaims added in v1.4.0

func (c *Context) JWTClaims(target any) error

JWTClaims 将鉴权中间件验证后的 Claims 解码到目标结构,用于业务侧读取强类型声明。

func (*Context) NoContent

func (c *Context) NoContent(statusCode int) error

NoContent 写入不包含响应体的状态码。

func (*Context) Param

func (c *Context) Param(name string) string

Param 返回路由中的命名路径参数。

func (*Context) Queries

func (c *Context) Queries() url.Values

Queries 返回全部查询参数。

func (*Context) Query

func (c *Context) Query(name string) string

Query 返回查询参数的第一个值。

func (*Context) ReadFormFile

func (c *Context) ReadFormFile(name string, maxFileBytes int64) (string, []byte, error)

ReadFormFile 在限制文件和请求体大小后读取 multipart 表单中的第一个文件。

func (*Context) Request

func (c *Context) Request() *http.Request

Request 返回额外 HTTP Handler 的原始请求;非 HTTP Context 返回 nil。

func (*Context) Response

func (c *Context) Response() http.ResponseWriter

Response 返回额外 HTTP Handler 的原始响应写入器;非 HTTP Context 返回 nil。

func (*Context) SetHeader

func (c *Context) SetHeader(name, value string)

SetHeader 设置响应头。

func (*Context) SpanID

func (c *Context) SpanID() string

SpanID 返回当前服务内单次请求到响应的处理标识。

func (*Context) String

func (c *Context) String(key any) string

func (*Context) Text

func (c *Context) Text(statusCode int, value string) error

Text 以纯文本格式写入响应。

func (*Context) TraceID

func (c *Context) TraceID() string

func (*Context) UserAgent

func (c *Context) UserAgent() string

func (*Context) Value

func (c *Context) Value(key any) any

type ErrorConvertFunc

type ErrorConvertFunc func(error) (RespError, bool)

ErrorConvertFunc 将函数适配为 ErrorConverter。

func (ErrorConvertFunc) Convert

func (f ErrorConvertFunc) Convert(err error) (RespError, bool)

Convert 执行错误转换。

type ErrorConverter

type ErrorConverter interface {
	Convert(error) (RespError, bool)
}

ErrorConverter 将应用依赖返回的错误转换为统一响应错误。

type GRPCRegisterFunc

type GRPCRegisterFunc func(grpc.ServiceRegistrar)

GRPCRegisterFunc 向统一的 gRPC Server 注册业务服务。

type GatewayRegisterFunc

type GatewayRegisterFunc func(context.Context, *runtime.ServeMux, string, []grpc.DialOption) error

GatewayRegisterFunc 注册由 google.api.http 生成的 Gateway 路由。

type HTTPServerOption

type HTTPServerOption func(*http.Server)

HTTPServerOption 调整底层 HTTP Server 的标准参数,不允许替换 Handler。

type HandlerFunc

type HandlerFunc func(c *Context) error

HandlerFunc 处理通过 Server.HandlePath 注册的额外 HTTP 请求;返回的错误由 Server 统一转换并写入响应。

type Option

type Option func(*config) error

Option 配置 Server 的初始化参数。

func WithAddress

func WithAddress(address string) Option

func WithAuditFunc added in v1.4.3

func WithAuditFunc(invoke AuditFunc) Option

WithAuditFunc 注入业务审计记录方法。

func WithCertificate

func WithCertificate(certFile, keyFile string) Option

func WithCertificatePEM

func WithCertificatePEM(certPEM, keyPEM []byte) Option

WithCertificatePEM 使用内存中的 PEM 证书和私钥启用 TLS。

func WithErrorConverters

func WithErrorConverters(converters ...ErrorConverter) Option

WithErrorConverters 注入应用依赖错误到统一响应错误的转换器。

func WithGRPCRegister

func WithGRPCRegister(registers ...GRPCRegisterFunc) Option

func WithGRPCServerOptions

func WithGRPCServerOptions(opts ...grpc.ServerOption) Option

func WithGatewayDialOptions

func WithGatewayDialOptions(opts ...grpc.DialOption) Option

func WithGatewayEndpoint

func WithGatewayEndpoint(endpoint string) Option

func WithGatewayOptions

func WithGatewayOptions(opts ...runtime.ServeMuxOption) Option

func WithGatewayRegister

func WithGatewayRegister(registers ...GatewayRegisterFunc) Option

func WithGatewayServerName

func WithGatewayServerName(serverName string) Option

func WithGracefulTimeout

func WithGracefulTimeout(timeout time.Duration) Option

func WithHTTPServerOptions

func WithHTTPServerOptions(opts ...HTTPServerOption) Option

func WithI18nBundle

func WithI18nBundle(bundle *i18n.Bundle) Option

WithI18nBundle 注入业务翻译目录;未匹配语言时回退到错误码定义的英文文案。

func WithI18nFS

func WithI18nFS(messageFS fs.FS) Option

WithI18nFS 从文件系统递归加载 TOML 翻译文件,并使用英文作为默认语言。

func WithJWTAuth added in v1.4.0

func WithJWTAuth(parser jwtx.Parser) Option

WithJWTAuth 使用自定义解析器启用 JWT 鉴权,支持非对称算法和外部密钥源。

func WithJWTSecret

func WithJWTSecret(secret []byte) Option

WithJWTSecret 使用 HS256 密钥启用 JWT 鉴权。

func WithListener

func WithListener(listener net.Listener) Option

func WithLogger

func WithLogger(logger grpclogging.Logger) Option

func WithName

func WithName(name string) Option

WithName 设置生命周期日志和 Serve 异常使用的 Server 实例标识。

func WithPermissionFunc added in v1.4.3

func WithPermissionFunc(invoke PermissionFunc) Option

WithPermissionFunc 注入业务权限校验方法。

func WithReflection

func WithReflection() Option

WithReflection 启用标准 gRPC Reflection Service。

func WithStreamInterceptors

func WithStreamInterceptors(interceptors ...grpc.StreamServerInterceptor) Option

func WithTLSConfig

func WithTLSConfig(tlsConfig *tls.Config) Option

func WithUnaryInterceptors

func WithUnaryInterceptors(interceptors ...grpc.UnaryServerInterceptor) Option

type PermissionFunc added in v1.4.3

type PermissionFunc func(context.Context, string, []string) error

PermissionFunc 根据方法声明的权限执行业务校验。

type RespError

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

RespError 描述可同时供 gRPC 和 Gateway 返回的业务错误。

func NewError

func NewError(code codes.Code, message string) RespError

NewError 创建指定 gRPC Code 和消息的响应错误。

func (RespError) Error

func (e RespError) Error() string

func (RespError) GRPCStatus

func (e RespError) GRPCStatus() *status.Status

GRPCStatus 将响应错误转换为 gRPC Status。

func (RespError) WithData

func (e RespError) WithData(data map[string]any) RespError

WithData 设置错误文案模板使用的变量,并复制数据以保持错误模板不可变。

func (RespError) WithDetails

func (e RespError) WithDetails(details ...proto.Message) RespError

WithDetails 追加结构化错误详情。

func (RespError) WithDomainReason

func (e RespError) WithDomainReason(domain, reason string) RespError

WithDomainReason 设置由业务定义的错误码和 i18n 信息。

func (RespError) WithErrorCode

func (e RespError) WithErrorCode(errorCode protoreflect.Enum) RespError

WithErrorCode 从枚举选项读取业务错误码、英文默认文案和额外 HTTP 状态码。

func (RespError) WithHTTPStatus

func (e RespError) WithHTTPStatus(statusCode int) RespError

WithHTTPStatus 设置通过 HandlePath 返回错误时使用的 HTTP 状态码。

func (RespError) WithMessage

func (e RespError) WithMessage(message string) RespError

WithMessage 设置返回给调用方的错误消息。

type Server

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

Server 在同一个端口提供原生 gRPC 和 grpc-gateway HTTP 服务。

func New

func New(opts ...Option) (*Server, error)

New 使用 Options 初始化服务,并将启动和停止函数注册到 lifex。

func (*Server) HandlePath

func (s *Server) HandlePath(method, path string, handler HandlerFunc) error

HandlePath 注册无法通过 google.api.http 表达的额外 HTTP 接口。

func (*Server) Start

func (s *Server) Start() error

Start 完成监听和 Gateway 注册,然后异步启动同端口的 HTTP 与 gRPC 服务。

func (*Server) Stop

func (s *Server) Stop() error

Stop 在配置的超时内停止 HTTP、Gateway 连接和 gRPC 服务。

Directories

Path Synopsis
Package testserver 提供标准 gRPC 与额外 HTTP 接口的测试环境。
Package testserver 提供标准 gRPC 与额外 HTTP 接口的测试环境。

Jump to

Keyboard shortcuts

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