endpoint

package
v0.3.3 Latest Latest
Warning

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

Go to latest
Published: Mar 22, 2026 License: MIT Imports: 19 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var TSInt64MappingMode = TSInt64ModeNumber

TSInt64MappingMode controls how int64/uint64 are rendered in generated TypeScript. Default is `number` because most HTTP JSON payloads from Go services encode these as JSON numbers.

Functions

func BroadcastWebSocketJSON added in v0.1.1

func BroadcastWebSocketJSON(path string, message any) error

BroadcastWebSocketJSON sends a JSON message to all clients of the path. BroadcastWebSocketJSON 向指定路径的所有客户端发送 JSON。

func ExportAxiosFromEndpointsToTSFile

func ExportAxiosFromEndpointsToTSFile(basePath string, endpoints []EndpointLike, relativeTSPath string) error

ExportAxiosFromEndpointsToTSFile writes generated TS code from endpoints to a file. ExportAxiosFromEndpointsToTSFile 将 Endpoint 生成的 TS 代码写入文件。

func ExportUnifiedAPIsToTSFiles added in v0.2.11

func ExportUnifiedAPIsToTSFiles(serverAPI ServerAPI, wsAPI WebSocketAPI, options UnifiedTSExportOptions) error

ExportUnifiedAPIsToTSFiles exports ServerAPI and WebSocketAPI into two TS files, and deduplicates interfaces/types/validators/ensure functions into one shared schema file. ExportUnifiedAPIsToTSFiles 会导出 ServerAPI 与 WebSocketAPI 到两个 TS 文件, 并将接口/类型/validator/ensure 去重后输出到一个共享 schema 文件。

func ExportWebSocketClientFromEndpointsToTSFile added in v0.1.1

func ExportWebSocketClientFromEndpointsToTSFile(baseURL string, endpoints []WebSocketEndpointLike, relativeTSPath string) error

ExportWebSocketClientFromEndpointsToTSFile writes generated TS code from endpoints to a file. ExportWebSocketClientFromEndpointsToTSFile 将 WebSocketEndpoint 生成的 TS 代码写入文件。

func GenerateAxiosFromEndpoints

func GenerateAxiosFromEndpoints(basePath string, endpoints []EndpointLike) (string, error)

GenerateAxiosFromEndpoints generates TypeScript axios client source code from endpoints. GenerateAxiosFromEndpoints 根据 Endpoint 列表生成 TypeScript axios 客户端代码。

func GenerateWebSocketClientFromEndpoints added in v0.1.1

func GenerateWebSocketClientFromEndpoints(baseURL string, endpoints []WebSocketEndpointLike) (string, error)

GenerateWebSocketClientFromEndpoints generates TypeScript websocket client source code from endpoints. GenerateWebSocketClientFromEndpoints 根据 WebSocketEndpoint 列表生成 TypeScript 客户端代码。

func RegisterWebSocketServerPayloadType added in v0.2.15

func RegisterWebSocketServerPayloadType[Payload any](endpoint *WebSocketEndpoint, messageType string)

RegisterWebSocketServerPayloadType registers a typed server payload schema for one message type. RegisterWebSocketServerPayloadType 注册服务端消息类型对应的 payload 类型。

func RegisterWebSocketTypedHandler added in v0.1.1

func RegisterWebSocketTypedHandler[Payload any](
	endpoint *WebSocketEndpoint,
	messageType string,
	handler func(payload Payload, ctx *WebSocketContext) (any, error),
)

RegisterWebSocketTypedHandler registers a typed handler for a message type. RegisterWebSocketTypedHandler 注册指定消息类型的强类型处理器。

func SendWebSocketJSON added in v0.1.1

func SendWebSocketJSON(path string, clientID string, message any) error

SendWebSocketJSON sends a JSON message to a specific client of the path. SendWebSocketJSON 向指定路径的某个客户端发送 JSON。

func SetTSInt64MappingMode added in v0.2.2

func SetTSInt64MappingMode(mode TSInt64Mode)

SetTSInt64MappingMode changes int64/uint64 mapping mode for TypeScript generation. Unsupported values fallback to TSInt64ModeNumber.

func SnapshotWebSocketClients added in v0.1.1

func SnapshotWebSocketClients(path string) map[string]*wsClient

SnapshotWebSocketClients returns a copy of current clients for the path. SnapshotWebSocketClients 返回指定路径当前客户端的副本。

Types

type CustomEndpoint added in v0.1.1

type CustomEndpoint[PP, QP, HP, CP, Req, Resp any] struct {
	Name               string
	Method             HTTPMethod
	Path               string
	Description        string
	RequestDescription string
	PathParams         PP
	QueryParams        QP
	HeaderParams       HP
	CookieParams       CP
	RequestBody        Req
	Responses          []Response[Resp]
	RequestKind        TSKind
	ResponseKind       TSKind
	HandlerFunc        gin.HandlerFunc
}

CustomEndpoint defines an API endpoint with a customizable body binder. CustomEndpoint 定义一个可自定义请求体绑定方式的 API。

func NewCustomEndpoint added in v0.1.1

func NewCustomEndpoint[PP, QP, HP, CP, Req, Resp any](
	name string,
	method HTTPMethod,
	path string,
	handler gin.HandlerFunc,
) CustomEndpoint[PP, QP, HP, CP, Req, Resp]

NewCustomEndpoint builds a CustomEndpoint with common fields. NewCustomEndpoint 构建 CustomEndpoint,便于快速初始化。

func (CustomEndpoint[PP, QP, HP, CP, Req, Resp]) EndpointMeta added in v0.1.1

func (s CustomEndpoint[PP, QP, HP, CP, Req, Resp]) EndpointMeta() EndpointMeta

EndpointMeta exposes metadata for TS generation. EndpointMeta 暴露 TS 生成所需的元数据。

func (CustomEndpoint[PP, QP, HP, CP, Req, Resp]) EndpointTSHints added in v0.1.1

func (s CustomEndpoint[PP, QP, HP, CP, Req, Resp]) EndpointTSHints() EndpointTSHints

EndpointTSHints customizes TS generation. EndpointTSHints 自定义 TS 生成。

func (CustomEndpoint[PP, QP, HP, CP, Req, Resp]) GinHandler added in v0.1.1

func (s CustomEndpoint[PP, QP, HP, CP, Req, Resp]) GinHandler() gin.HandlerFunc

GinHandler builds a gin.HandlerFunc that binds params/body and calls HandlerFunc. GinHandler 会绑定参数/请求体并调用 HandlerFunc。

type Endpoint

type Endpoint[PP, QP, HP, CP, Req, Resp any] struct {
	Name               string
	Method             HTTPMethod
	Path               string
	Description        string
	RequestDescription string
	PathParams         PP
	QueryParams        QP
	HeaderParams       HP
	CookieParams       CP
	RequestBody        Req
	Responses          []Response[Resp]
	HandlerFunc        func(pathParams PP, queryParams QP, headerParams HP, cookieParams CP, requestBody Req, ctx *gin.Context) (Response[Resp], error)
}

Endpoint is a strongly-typed server API definition. HandlerFunc receives typed params/body and returns a typed Response. Endpoint 是强类型服务器端 API 定义,HandlerFunc 接收强类型参数并返回强类型 Response。

func NewEndpoint added in v0.0.9

func NewEndpoint[PP, QP, HP, CP, Req, Resp any](
	name string,
	method HTTPMethod,
	path string,
	handler func(pathParams PP, queryParams QP, headerParams HP, cookieParams CP, requestBody Req, ctx *gin.Context) (Resp, error),
) Endpoint[PP, QP, HP, CP, Req, Resp]

NewEndpoint builds an Endpoint with a simplified handler that only returns a 200 response body. NewEndpoint 使用简化 handler 构建 Endpoint,只支持 200 响应返回值。

func NewEndpointNoBody added in v0.0.9

func NewEndpointNoBody[PP, QP, HP, CP, Resp any](
	name string,
	method HTTPMethod,
	path string,
	handler func(pathParams PP, queryParams QP, headerParams HP, cookieParams CP, ctx *gin.Context) (Resp, error),
) Endpoint[PP, QP, HP, CP, NoBody, Resp]

NewEndpointNoBody builds an Endpoint with NoBody request and 200 response. NewEndpointNoBody 构建无请求体的 Endpoint,只返回 200。

func NewEndpointNoParams added in v0.0.9

func NewEndpointNoParams[Req, Resp any](
	name string,
	method HTTPMethod,
	path string,
	handler func(requestBody Req, ctx *gin.Context) (Resp, error),
) Endpoint[NoParams, NoParams, NoParams, NoParams, Req, Resp]

NewEndpointNoParams builds an Endpoint without params and with 200 response. NewEndpointNoParams 构建无参数的 Endpoint,只返回 200。

func (Endpoint[PP, QP, HP, CP, Req, Resp]) EndpointMeta

func (s Endpoint[PP, QP, HP, CP, Req, Resp]) EndpointMeta() EndpointMeta

EndpointMeta exposes metadata for TS generation. EndpointMeta 暴露 TS 生成所需的元数据。

func (Endpoint[PP, QP, HP, CP, Req, Resp]) GinHandler

func (s Endpoint[PP, QP, HP, CP, Req, Resp]) GinHandler() gin.HandlerFunc

GinHandler builds a gin.HandlerFunc that auto-binds params/body and calls HandlerFunc. GinHandler 会自动绑定参数/请求体并调用 HandlerFunc。

type EndpointLike

type EndpointLike interface {
	EndpointMeta() EndpointMeta
	GinHandler() gin.HandlerFunc
}

EndpointLike is implemented by Endpoint to expose metadata and gin handler. EndpointLike 由 Endpoint 实现,用于暴露元数据与 gin handler。

type EndpointMeta

type EndpointMeta struct {
	Name               string
	Method             HTTPMethod
	Path               string
	Description        string
	RequestDescription string
	PathParamsType     reflect.Type
	QueryParamsType    reflect.Type
	HeaderParamsType   reflect.Type
	CookieParamsType   reflect.Type
	RequestBodyType    reflect.Type
	Responses          []ResponseMeta
}

EndpointMeta is the metadata view used to generate TypeScript from Endpoint. EndpointMeta 是用于 TS 生成的元数据视图。

type EndpointTSHints added in v0.1.1

type EndpointTSHints struct {
	RequestKind  TSKind
	ResponseKind TSKind
}

EndpointTSHints provides extra metadata for TS generation. EndpointTSHints 提供 TS 生成的额外元数据。

type EndpointTSHintsProvider added in v0.1.1

type EndpointTSHintsProvider interface {
	EndpointTSHints() EndpointTSHints
}

EndpointTSHintsProvider allows endpoints to customize TS generation behavior. EndpointTSHintsProvider 允许 endpoint 自定义 TS 生成行为。

type FormData added in v0.1.1

type FormData struct{}

FormData is a marker type used for TS generation of multipart/form-data. FormData 是用于 multipart/form-data 的 TS 生成标记类型。

type HTTPMethod

type HTTPMethod string

HTTPMethod defines the allowed HTTP method values used by Endpoint.Method. HTTPMethod 定义 Endpoint.Method 可使用的 HTTP 方法值,避免直接写字符串导致拼写错误。

const (
	// HTTPMethodGet represents HTTP GET.
	// HTTPMethodGet 表示 HTTP GET 方法。
	HTTPMethodGet HTTPMethod = HTTPMethod(http.MethodGet)
	// HTTPMethodPost represents HTTP POST.
	// HTTPMethodPost 表示 HTTP POST 方法。
	HTTPMethodPost HTTPMethod = HTTPMethod(http.MethodPost)
	// HTTPMethodPut represents HTTP PUT.
	// HTTPMethodPut 表示 HTTP PUT 方法。
	HTTPMethodPut HTTPMethod = HTTPMethod(http.MethodPut)
	// HTTPMethodPatch represents HTTP PATCH.
	// HTTPMethodPatch 表示 HTTP PATCH 方法。
	HTTPMethodPatch HTTPMethod = HTTPMethod(http.MethodPatch)
	// HTTPMethodDelete represents HTTP DELETE.
	// HTTPMethodDelete 表示 HTTP DELETE 方法。
	HTTPMethodDelete HTTPMethod = HTTPMethod(http.MethodDelete)
	// HTTPMethodHead represents HTTP HEAD.
	// HTTPMethodHead 表示 HTTP HEAD 方法。
	HTTPMethodHead HTTPMethod = HTTPMethod(http.MethodHead)
	// HTTPMethodOptions represents HTTP OPTIONS.
	// HTTPMethodOptions 表示 HTTP OPTIONS 方法。
	HTTPMethodOptions HTTPMethod = HTTPMethod(http.MethodOptions)
)

func (HTTPMethod) IsValid

func (m HTTPMethod) IsValid() bool

IsValid returns whether m is one of the supported HTTP method constants. IsValid 用于判断 m 是否是当前库支持的 HTTPMethod 常量之一。

type NoBody

type NoBody struct{}

NoBody is a marker type meaning "no request body". NoBody 是一个标记类型,表示“没有请求体”。

type NoMessage added in v0.1.1

type NoMessage struct{}

NoMessage is a marker type meaning "no websocket message payload". NoMessage 是一个标记类型,表示“不发送/不接收 websocket 消息体”。

type NoParams

type NoParams struct{}

NoParams is a marker type meaning "no params". NoParams 是一个标记类型,表示“没有参数”。

type RawBytes added in v0.1.1

type RawBytes []byte

RawBytes is a marker type used for raw byte request bodies. RawBytes 是用于原始二进制请求体的标记类型。

type Response

type Response[T any] struct {
	StatusCode  int    `json:"statusCode"`
	Body        T      `json:"body,omitempty"`
	Description string `json:"description,omitempty"`
}

Response is a typed response wrapper for Endpoint handlers. Response 是 Endpoint 处理函数的强类型响应封装。

type ResponseMeta

type ResponseMeta struct {
	StatusCode  int
	BodyType    reflect.Type
	Description string
}

ResponseMeta is the response metadata used to generate TypeScript. ResponseMeta 是用于 TS 生成的响应元数据。

type ServerAPI

type ServerAPI struct {
	// BasePath is the URL prefix used for generated TS clients.
	// BasePath 用于生成 TS 客户端时的 URL 前缀。
	BasePath string

	// GroupPath is the router-group path used when registering handlers in gin.
	// GroupPath 是在 gin 中注册路由时使用的分组路径。
	GroupPath string

	// Endpoints contains all HTTP endpoints under this API group.
	// Endpoints 包含该 API 分组下的全部 HTTP 端点。
	Endpoints []EndpointLike
}

ServerAPI is the single struct you use to describe server-side APIs. It can build a gin.RouterGroup and export axios TypeScript. ServerAPI 是你用于描述服务器端 API 的唯一结构体; 可构建 gin.RouterGroup,并生成 axios TypeScript。

func (ServerAPI) Build

func (s ServerAPI) Build(engine *gin.Engine, relativeTSPath string) (*gin.RouterGroup, error)

Build builds gin.RouterGroup and exports TS in one call. Build 一次性完成 RouterGroup 构建与 TS 导出。

func (ServerAPI) BuildGinGroup

func (s ServerAPI) BuildGinGroup(engine *gin.Engine) (*gin.RouterGroup, error)

BuildGinGroup registers all endpoints and returns the RouterGroup. BuildGinGroup 会注册所有端点并返回 RouterGroup。

func (ServerAPI) ExportTS

func (s ServerAPI) ExportTS(relativeTSPath string) error

ExportTS generates axios TypeScript to a relative path. If relativeTSPath is empty, it defaults to vue/composables/my-schemas.ts. ExportTS 会生成 axios TypeScript 到相对路径; 若 relativeTSPath 为空,则默认 vue/composables/my-schemas.ts。

type StreamResponse added in v0.1.1

type StreamResponse struct{}

StreamResponse is a marker type used for streaming responses. StreamResponse 是用于流式响应的标记类型。

type TSInt64Mode added in v0.2.2

type TSInt64Mode string
const (
	TSInt64ModeNumber TSInt64Mode = "number"
	TSInt64ModeString TSInt64Mode = "string"
)

type TSKind added in v0.1.1

type TSKind string

TSKind describes how request/response bodies should be handled in TS. TSKind 描述在 TS 中如何处理请求/响应体。

const (
	TSKindJSON           TSKind = "json"
	TSKindMultipart      TSKind = "multipart"
	TSKindFormURLEncoded TSKind = "form_urlencoded"
	TSKindText           TSKind = "text"
	TSKindBytes          TSKind = "bytes"
	TSKindStream         TSKind = "stream"
)

type UnifiedTSExportOptions added in v0.2.11

type UnifiedTSExportOptions struct {
	ServerTSPath    string
	WebSocketTSPath string
	SchemaTSPath    string
}

UnifiedTSExportOptions controls output paths for unified TS export. UnifiedTSExportOptions 用于配置统一 TS 导出的输出路径。

type WebSocketAPI added in v0.1.1

type WebSocketAPI struct {
	// BasePath is the URL prefix used for generated TS websocket clients.
	// BasePath 用于生成 TS websocket 客户端时的 URL 前缀。
	BasePath string

	// GroupPath is the router-group path used when registering websocket handlers in gin.
	// GroupPath 是在 gin 中注册 websocket 路由时使用的分组路径。
	GroupPath string

	// Endpoints contains all websocket endpoints under this API group.
	// Endpoints 包含该 API 分组下的全部 websocket 端点。
	Endpoints []WebSocketEndpointLike

	// DefaultClientMessageType is the default envelope type for endpoint.ClientMessageType.
	// DefaultClientMessageType 作为 endpoint.ClientMessageType 的默认封装类型。
	DefaultClientMessageType reflect.Type

	// DefaultServerMessageType is the default envelope type for endpoint.ServerMessageType.
	// DefaultServerMessageType 作为 endpoint.ServerMessageType 的默认封装类型。
	DefaultServerMessageType reflect.Type
}

WebSocketAPI describes websocket endpoints, supports gin registration and TS export. WebSocketAPI 描述 websocket 端点,可构建 gin.RouterGroup,并生成 TS。

func (WebSocketAPI) Build added in v0.1.1

func (s WebSocketAPI) Build(engine *gin.Engine, relativeTSPath string) (*gin.RouterGroup, error)

Build builds gin.RouterGroup and exports TS in one call. Build 一次性完成 RouterGroup 构建与 TS 导出。

func (WebSocketAPI) BuildGinGroup added in v0.1.1

func (s WebSocketAPI) BuildGinGroup(engine *gin.Engine) (*gin.RouterGroup, error)

BuildGinGroup registers all websocket endpoints and returns the RouterGroup. BuildGinGroup 注册所有 websocket 端点并返回 RouterGroup。

func (WebSocketAPI) ExportTS added in v0.1.1

func (s WebSocketAPI) ExportTS(relativeTSPath string) error

ExportTS generates websocket TypeScript to a relative path. ExportTS 会生成 websocket TypeScript 到相对路径。

type WebSocketContext added in v0.1.1

type WebSocketContext struct {
	ID      string
	Conn    *websocket.Conn
	Request *http.Request
	// contains filtered or unexported fields
}

WebSocketContext provides access to the current connection and publish helpers. WebSocketContext 提供当前连接与发布消息的方法。

func (*WebSocketContext) Publish added in v0.1.1

func (c *WebSocketContext) Publish(message any) error

Publish broadcasts to all connected clients. Publish 向所有已连接客户端广播消息。

func (*WebSocketContext) Send added in v0.1.1

func (c *WebSocketContext) Send(message any) error

Send replies to the current client. Send 向当前客户端发送消息。

type WebSocketEndpoint added in v0.1.1

type WebSocketEndpoint struct {
	Name         string
	Path         string
	Description  string
	MessageTypes []string

	// Message types for TS generation. If ClientMessageType is nil, defaults to WebSocketMessage.
	// 用于 TS 生成的消息类型;若 ClientMessageType 为空则默认 WebSocketMessage。
	ClientMessageType  reflect.Type
	ServerMessageType  reflect.Type
	ClientPayloadTypes map[string]reflect.Type
	ServerPayloadTypes map[string]reflect.Type

	// Optional upgrader configuration. If zero-value, a default upgrader is used.
	// Upgrader 可选配置;若为空则使用默认 Upgrader。
	Upgrader websocket.Upgrader

	// Optional hooks.
	// 可选回调。
	OnConnect    func(ctx *WebSocketContext) error
	HandlerFunc  func(message any, ctx *WebSocketContext) (any, error)
	OnDisconnect func(ctx *WebSocketContext, err error)

	// Optional typed handlers based on message type.
	// When MessageHandlers is set, HandlerFunc is ignored.
	// 可选按消息类型分发的处理器;若设置则忽略 HandlerFunc。
	MessageHandlers   map[string]func(payload json.RawMessage, ctx *WebSocketContext) (any, error)
	MessageTypeGetter func(message any) (msgType string, payload json.RawMessage, err error)

	PingPeriod time.Duration
	PongWait   time.Duration
	ReadLimit  int64
	// contains filtered or unexported fields
}

WebSocketEndpoint is a websocket endpoint definition. WebSocketEndpoint 是 WebSocket 端点定义。

func NewWebSocketEndpoint added in v0.1.1

func NewWebSocketEndpoint() *WebSocketEndpoint

NewWebSocketEndpoint constructs a WebSocketEndpoint with initialized hub. NewWebSocketEndpoint 构建并初始化 WebSocketEndpoint。

func (*WebSocketEndpoint) ConnectedCount added in v0.1.1

func (s *WebSocketEndpoint) ConnectedCount() int

ConnectedCount returns the current connected client count. ConnectedCount 返回当前已连接客户端数量。

func (*WebSocketEndpoint) GinHandler added in v0.1.1

func (s *WebSocketEndpoint) GinHandler() gin.HandlerFunc

GinHandler upgrades and handles websocket connections. GinHandler 负责升级并处理 websocket 连接。

func (*WebSocketEndpoint) Publish added in v0.1.1

func (s *WebSocketEndpoint) Publish(message any) error

Publish broadcasts a server message to all connected clients. Publish 向所有已连接客户端广播消息。

func (*WebSocketEndpoint) SendTo added in v0.1.1

func (s *WebSocketEndpoint) SendTo(clientID string, message any) error

SendTo sends a server message to a specific client. SendTo 向指定客户端发送消息。

func (*WebSocketEndpoint) SetFullPath added in v0.1.1

func (s *WebSocketEndpoint) SetFullPath(path string)

SetFullPath stores the full websocket path (including group path). SetFullPath 保存 websocket 完整路径(包含 group path)。

func (*WebSocketEndpoint) WebSocketMeta added in v0.1.1

func (s *WebSocketEndpoint) WebSocketMeta() WebSocketEndpointMeta

WebSocketMeta exposes metadata for TS generation. WebSocketMeta 暴露 TS 生成所需的元数据。

type WebSocketEndpointLike added in v0.1.1

type WebSocketEndpointLike interface {
	WebSocketMeta() WebSocketEndpointMeta
	GinHandler() gin.HandlerFunc
	SetFullPath(path string)
}

WebSocketEndpointLike is implemented by WebSocketEndpoint to expose metadata and gin handler. WebSocketEndpointLike 由 WebSocketEndpoint 实现,用于暴露元数据与 gin handler。

type WebSocketEndpointMeta added in v0.1.1

type WebSocketEndpointMeta struct {
	Name               string
	Path               string
	Description        string
	ClientMessageType  reflect.Type
	ServerMessageType  reflect.Type
	MessageTypes       []string
	ClientPayloadTypes map[string]reflect.Type
	ServerPayloadTypes map[string]reflect.Type
}

WebSocketEndpointMeta is the metadata view used to generate TypeScript. WebSocketEndpointMeta 是用于 TS 生成的元数据视图。

type WebSocketMessage added in v0.1.1

type WebSocketMessage struct {
	Type    string          `json:"type"`
	Payload json.RawMessage `json:"payload"`
}

WebSocketMessage is a default envelope for multi-handler messages. WebSocketMessage 是多 handler 消息的默认封装。

Jump to

Keyboard shortcuts

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