api

package module
v1.5.22 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: MIT Imports: 23 Imported by: 0

README

@go/api

托管 WebSocket 使用 HTTP OpenContext;调用取消传入握手,响应体按原生约定关闭。

依赖已发布 HTTP v1.5.13 的统一 Open 接口;握手错误的响应 Body 由错误处理方消费和关闭,保留拒绝状态、Header 与错误详情。

本地模拟

不匹配声明输入时返回 *MockInputError 和结果码 mock_input_rejected,调用方可将其记录为预期反例;配置错误、取消和权限错误仍是执行失败。

CallOptions.Mode="mock" 使用 Action 的 mock: {enabled: true, request: {to: "测试号码"}, response: {statusCode: 200, data: {...}}} 固定应答。request 必须非空,其声明字段必须匹配调用输入;可用于只允许指定测试号码。模拟不打开凭据、不签名、不执行 Filter、不连接网络,也不支持流式。Token、enabled、abstract 和取消检查仍生效,options.config 不可覆盖 mock。结果明确包含 mode:"mock", simulated:true,失败应答沿用 response 规则。默认或 Mode="live" 保持真实调用;不自动回退模拟。模拟成功不能证明供应商认证或实际送达。

@go/api 是一个极致精简、接口驱动、AI 友好的 API 调用引擎。它旨在消除对接第三方服务(如腾讯云、阿里云、OpenAI 等)时的繁琐 SDK 依赖和硬编码摩擦。

动态 Action 可通过 protectedInputs 声明允许接收受保护引用的精确 payload 路径。JavaScript api.Call 只在这些路径通过当前调用上下文中的 ProtectedValueResolver 展开 @protected: 引用;未声明位置始终保持为不可用的引用字符串。请求 Filter 只能处理引用,展开发生在签名和 HTTP 编码之前,确保签名覆盖最终请求内容。

🎯 设计哲学

  • 数据驱动 (Data-Driven):一切皆数据,通过强类型 Action 结构体描述请求。
  • 无状态 (Stateless):核心库不绑定任何具体的云服务实现,仅提供标准协议支持。
  • AI 友好 (AI-First):极其简单的结构体定义,消除了幻觉,让 AI 能够精准生成调用代码。
  • 非破坏性注入:支持从配置自动回填缺失参数(如 AppId, SecretId),但不覆盖显式设置的值。

动态 Action 的传输、鉴权控制及文档字段属于配置,不默认发送到供应商。业务默认值可放在 payload(支持继承);显式调用 payload 中的同名业务字段仍保留。该行为自 v1.5.20 发布。

📦 安装

go get github.com/api-go/api

💡 核心流程

  1. 定义 Action:实现 Action 接口(及可选的 SignerAction, ConfigurableAction 等)。
  2. 配置授权:在 api.yml 或环境变量中配置密钥。
  3. 发起调用:使用 api.Call(action, options),统一获得 Result。

🛠 接口说明

  • Action:核心标识接口,定义动作名称(如 tencent.sms.smsPackagesStatistics)。
  • SignerAction:指定签名算法名称(如 tc3)。
  • ConfigurableAction:提供硬编码的默认参数或元数据。
  • URLAction / MethodAction:动态指定 Endpoint 和 HTTP 方法。
  • ValidatableAction:业务参数自校验。
  • CallOptions:提供内部 Token、超时、临时配置覆盖、Logger、流式回调与可选 Timing。InputPreview 可显式开启输入诊断:仅记录 input 第一条文本前 20 个 Unicode 字符和批次数量,不展开受保护值或记录其余输入;默认关闭。
  • 托管 WebSocket Transport:Action 设置 transport: websocket 后,Call 自动按连接 ID 复用单在途连接、处理空闲回收,并继续使用既有 Signer、Filter、日志和统一 Result。
  • Result:统一返回 ok/statusCode/headers/data/code/error/errorDetail,开启 Timing 时额外返回 timing;业务响应保留在 data,HTTP 非成功响应的原始详情保留在 errorDetail。
  • 流式 HTTP 非成功响应同样触发 result Filter,使会话所有者可以处理失效的服务端历史;保留调用错误,不触发成功流的 done/OnDone。
  • RegisterAction / RemoveAction:动态注册和热更新数据驱动的 Action。
  • RegisterJSSigner / RemoveSigner:管理 JavaScript Signer。
  • RegisterJSFilter / RemoveFilter:管理可复用的 JavaScript 请求/响应 Filter。
  • ParseActionYAML / PatchActionTokens / ConvertActionJSONToYAML:无状态解析、保注释补丁和旧格式转换;不内置任何供应商 Action。

🔒 安全性 (Ultimate Memory Safety)

  • 内置解密:只识别 **URLBase64(AESGCM) 配置密文。
  • 内存保护:敏感配置解密后以 safe.SafeBuf 形式存储,防止内存 Dump 泄露。
  • 防止字符串泄露:通过 unsafe.String 零拷贝技术,确保敏感 Header(如 Authorization)在调用结束后可被物理擦除,彻底解决 Go 字符串不可变性导致的堆泄露问题。
  • 全生命周期闭环:api.Call 结束后自动触发 httpReq.Close(),对所有中间缓冲区进行 ZeroMemory 随机覆盖。
  • 安全辅助函数:内置 SetBasicAuth, SetBearerAuth 等工具,强制执行无拼接的内存安全逻辑。

🧪 示例

type MySmsAction struct {
    Limit int
    AppId string // 自动从配置注入
}
func (MySmsAction) ActionName() string { return "tencent.sms.smsPackagesStatistics" }
func (MySmsAction) SignerName() string { return "tc3" }

result, err := api.Call(&MySmsAction{Limit: 10}, &api.CallOptions{
    Token: "internal-token",
    Config: map[string]any{"path": "/v1/messages"},
})

动态 Action 可以在调用时覆盖非敏感配置:

api.RegisterAction("openai", map[string]any{
    "url": "http://127.0.0.1:8001/v1/chat/completions",
    "method": "POST",
    "signer": "none",
    "tokens": []string{"internal-token"},
})

result, err := api.CallBy("openai", payload, &api.CallOptions{
    Token: "internal-token",
    Config: map[string]any{"path": "/v1/embeddings"},
})

tokens 未配置或为空时无需 Token。tokens/enabled/test/logging 与原配置中的密文字段不能通过 options.config 覆盖。流式调用使用 go/http.ManualDo,OnHeaders 与 OnDone 接收 lower-camel map,OnData 接收原始字节块。

调用时设置 CallOptions.Timing=true 可获得毫秒级粗粒度诊断信息:所有调用返回 timing.total,流式调用还返回从调用开始到首个响应数据块的 timing.firstToken。默认不采集也不返回 Timing;firstToken 表示首个网络数据块,并非协议解析后的精确模型 Token。

WebSocket Action 可设置 websocket.connectionID、websocket.idleTimeout 和 websocket.responseMode。responseMode 默认为 first;设为 filter 时,由 Filter 在处理 chunk 后返回 done: true 结束调用。连接持续活跃时不会被强制轮换,仅在空闲超时、Action 更新、连接故障或进程结束时关闭。

Action 只使用 filters: ["name"] 这一种形式。Filter 采用中间件包裹顺序:前置 request 按配置正序执行,后置 headers/chunk/result/done 按配置逆序执行,并自行根据 event 决定是否处理。流式 Filter 应通过输入/输出的 state 保存单次调用状态,不能假设 HTTP chunk 与 SSE 或 JSONL 消息边界一致。JavaScript Filter 的 chunk 是 UTF-8 字符串;Go Filter 仍接收原始 []byte,二进制响应不应挂载文本型 JavaScript Filter。

动态 Action 可通过 extends 继承另一个 Action;父配置先合并,子配置深度覆盖。继承在每次调用时解析,因此父 Action 热更新会立即作用于子 Action。循环继承或不存在的父 Action 会直接返回错误。

面向 JavaScript 低代码调用时,Action 可配置 resultMode: data,使 api.Call 直接返回业务 data,并保留顶层 ok/code/error,避免 HTTP 状态和响应头干扰应用逻辑。该配置支持 extends 继承,只影响 JavaScript 导出;Go 的 Call 与 CallBy 始终返回完整 Result。


更多详情请参阅 TEST.md 和 CHANGELOG.md。

model configuration readiness

ModelConfigured uses the Action inheritance resolver without calling a provider or exposing configuration. It rejects missing, abstract, disabled, and incomplete model Actions. Covered by TestModelConfiguredUsesEffectiveActionWithoutCallingProvider.

v1.5.19 依赖基线

本版本对齐 Log v1.5.17 与发布时模块索引中的上游已发布依赖;公开 API 保持兼容。

AES-GCM 配置密文兼容

正式依赖选用 crypto v1.5.9,共享 Symmetric.Decrypt/DecryptBytes 先认证 [12 字节 IV][密文][16 字节 tag],再使用配置 IV 兼容旧格式;现有 API 不变。新数据推荐 EncryptBytesAutoIV,先升级接收端再启用新写入。此能力针对 AES-GCM,不改变 CBC/SM4 格式。

Documentation

Index

Constants

View Source
const ProtectedValuesContextKey = "ProtectedValues"

ProtectedValuesContextKey identifies the request-scoped protected-value resolver.

Variables

View Source
var GlobalConfigs = map[string]any{}

GlobalConfigs 存储整棵配置树

Functions

func AddConfig

func AddConfig(name string, conf map[string]any)

AddConfig 是 SetConfig 的兼容性别名

func ConvertActionJSONToYAML

func ConvertActionJSONToYAML(source string) (string, error)

ConvertActionJSONToYAML converts a legacy JSON Action document to readable block-style YAML. It does not add defaults or modify the Action semantics.

func Encrypt

func Encrypt(plaintext string) (string, error)

Encrypt encrypts plaintext for storage in API configuration.

func ExportGoStructs

func ExportGoStructs(packageName string) string

ExportGoStructs 根据全局配置生成 Go 结构体代码

func GetActionConfig

func GetActionConfig(actionName string) (map[string]any, []*safe.SafeBuf)

GetActionConfig 获取某个动作经过层级合并后的完整配置,返回配置图和需要手动关闭的 SafeBuf 列表

func GetBytesOrSafe

func GetBytesOrSafe(v any) ([]byte, func())

GetBytesOrSafe 从配置中安全地获取字节切片。如果是 SafeBuf,则返回明文副本及对应的清理函数

func GetManifest

func GetManifest() map[string]any

GetManifest 返回 API 的描述信息,方便 AI 阅读

func GetStringOrSafe

func GetStringOrSafe(v any) (string, func())

GetStringOrSafe 从配置中安全地获取字符串值。如果是 SafeBuf,则返回明文副本及对应的清理函数

func Load

func Load(name string) error

Load 加载指定的配置文件并合并到 GlobalConfigs

func MergeMap

func MergeMap(dst, src map[string]any)

MergeMap 深度合并两个 map

func ModelConfigured

func ModelConfigured(name, model string) bool

ModelConfigured checks a dynamic model Action without making a request or exposing its configuration. Use the same inheritance resolver as CallBy.

func ParseActionYAML

func ParseActionYAML(source string) (map[string]any, error)

ParseActionYAML parses a data-driven Action definition without applying product-specific defaults or registering it globally.

func PatchActionTokens

func PatchActionTokens(source string, tokens []string) (string, error)

PatchActionTokens replaces the top-level tokens field while preserving the rest of the YAML document, including comments and field order.

func RegisterAction

func RegisterAction(name string, definition any)

RegisterAction 注册 API 动作。 definition 可以是一个结构体实例(用作类型模板)或一个 map[string]any(用作动态定义)。

func RegisterFilter

func RegisterFilter(name string, filter Filter)

RegisterFilter registers a reusable request/response filter.

func RegisterJSFilter

func RegisterJSFilter(name, code string)

RegisterJSFilter registers an administrator-managed JavaScript filter.

func RegisterJSSigner

func RegisterJSSigner(name, code string)

RegisterJSSigner registers an administrator-managed JavaScript signer.

func RegisterSigner

func RegisterSigner(name string, s Signer)

RegisterSigner 注册全局签名器

func RemoveAction

func RemoveAction(name string)

RemoveAction unregisters a dynamic Action.

func RemoveFilter

func RemoveFilter(name string)

RemoveFilter unregisters a custom filter.

func RemoveSigner

func RemoveSigner(name string)

RemoveSigner unregisters a custom signer. Built-in signers are retained.

func ReplaceConfig

func ReplaceConfig(name string, conf map[string]any)

ReplaceConfig replaces one configuration root. It is intended for dynamic stores such as DocDB where removed fields must disappear immediately.

func SetConfig

func SetConfig(name string, conf map[string]any)

SetConfig 允许在内存中动态添加或覆盖配置,适用于从数据库或知识库加载配置的场景。 它会自动扫描 map 中的字符串,识别并解密以 "**" 开头的加密内容并转换为 SafeBuf。

func SetEncryptKeys

func SetEncryptKeys(key, iv []byte)

SetEncryptKeys 允许设置自定义的配置加解密密钥

func SetJSRunner

func SetJSRunner(runner func(context.Context, string, map[string]any) (map[string]any, error))

SetJSRunner 设置 JS 执行器钩子,由 go/js 引擎在启动时注入。 这避免了 api 模块直接依赖 go/js 产生的循环引用。

Types

type Action

type Action interface {
	ActionName() string // 例如: "tencent.sms.send"
}

Action 是所有接口的基础标识接口

type CallLog

type CallLog struct {
	log.BaseLog
	Action       string  `log:"pos:6,color:cyan"`
	Method       string  `log:"pos:7,color:gray"`
	URL          string  `log:"pos:8,color:gray"`
	StatusCode   int     `log:"pos:9,color:magenta,keyname:Status"`
	Code         string  `log:"pos:10,color:magenta"`
	Error        string  `log:"pos:11,color:red"`
	UsedTime     float32 `log:"pos:12,color:green,precision:6"`
	Stream       bool    `log:"pos:13"`
	ResponseSize int64   `log:"pos:14,color:magenta,keyname:Size"`
	RequestData  any     `log:"pos:15,color:cyan,keyname:Request"`
	ResponseData any     `log:"pos:16,color:magenta,keyname:Response"`
}

func (*CallLog) Reset

func (entry *CallLog) Reset()

type CallOptions

type CallOptions struct {
	Context context.Context
	Token   string
	Config  map[string]any
	Timeout time.Duration
	Logger  *log.Logger
	Stream  *StreamOptions
	Timing  bool
	// Mode defaults to live. Mock uses only the Action's declared fixture.
	Mode string
	// InputPreview logs at most 20 Unicode characters from the first text input.
	InputPreview bool
}

CallOptions controls one API invocation without changing the stored Action.

type ConfigurableAction

type ConfigurableAction interface {
	Config() map[string]any
}

ConfigurableAction 定义可以提供默认硬编码配置的动作

type Filter

type Filter interface {
	Apply(ctx context.Context, event string, input map[string]any) (map[string]any, error)
}

Filter transforms one request or response event. Implementations must be stateless; per-call state is passed through input["state"] and returned as output["state"].

func GetFilter

func GetFilter(name string) Filter

GetFilter returns one registered filter.

type FormatAction

type FormatAction interface {
	GetFormat() string // 返回: "json", "form", "multipart"
}

FormatAction 定义请求体格式

type GenericAction

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

GenericAction 是一个动态 Action 容器,实现了所有 API 相关接口

func (*GenericAction) ActionName

func (a *GenericAction) ActionName() string

func (*GenericAction) Config

func (a *GenericAction) Config() map[string]any

func (*GenericAction) GetFormat

func (a *GenericAction) GetFormat() string

func (*GenericAction) GetMethod

func (a *GenericAction) GetMethod() string

func (*GenericAction) GetURL

func (a *GenericAction) GetURL() string

func (*GenericAction) MarshalJSON

func (a *GenericAction) MarshalJSON() ([]byte, error)

func (*GenericAction) SignerName

func (a *GenericAction) SignerName() string

type HttpRequest

type HttpRequest struct {
	Context context.Context
	Url     string
	Method  string

	Payload any
	// contains filtered or unexported fields
}

HttpRequest 内部使用的请求描述结构,供 Signer 使用

func (*HttpRequest) Close

func (r *HttpRequest) Close()

Close 物理覆盖并清除所有关联的敏感缓冲区,确保内存中不再留存明文

func (*HttpRequest) GetHeader

func (r *HttpRequest) GetHeader(key string) string

GetHeader 获取指定 Header 的值

func (*HttpRequest) SetHeader

func (r *HttpRequest) SetHeader(key string, values ...any)

SetHeader 提供无感知的安全 Header 设置功能。支持传入多个参数进行自动拼接。 如果参数中包含 *safe.SafeBuf, *safe.SecretPlaintext 或 []byte (标记为敏感), 整个生成的 Header 缓冲区都将被注册用于后置物理擦除。 安全的拼接与转换(如 safe.Concat, safe.Base64)建议使用 safe 包提供的返回 *safe.SafeBuf 的方法。

type MethodAction

type MethodAction interface {
	GetMethod() string // 例如: "GET"
}

MethodAction 定义显式指定方法的动作

type MockInputError

type MockInputError struct{}

MockInputError identifies a rejected test input, rather than a broken fixture or failed execution. Callers can record this expected negative outcome.

func (*MockInputError) Error

func (*MockInputError) Error() string

type ProtectedValueResolver

type ProtectedValueResolver interface {
	OpenProtected(reference string) (*safe.SecretPlaintext, error)
}

ProtectedValueResolver opens references owned by the current low-code call.

type Result

type Result struct {
	Mode        string
	Simulated   bool
	Ok          bool
	StatusCode  int
	Headers     map[string]string
	Data        any
	Code        string
	Error       string
	ErrorDetail any
	Timing      map[string]any
	// contains filtered or unexported fields
}

Result 定义 API 调用的标准返回结果

func Call

func Call(action Action, options ...*CallOptions) (*Result, error)

Call invokes an Action and returns the common API result envelope.

func CallBy

func CallBy(name string, payload any, options ...*CallOptions) (*Result, error)

CallBy invokes a registered dynamic or Go Action.

type Signer

type Signer interface {
	Sign(req *HttpRequest, config map[string]any) error
}

Signer 负责为请求附加签名信息

func GetSigner

func GetSigner(name string) Signer

GetSigner 获取签名器

type SignerAction

type SignerAction interface {
	SignerName() string // 例如: "tc3"
}

SignerAction 定义需要签名的动作

type StreamOptions

type StreamOptions struct {
	OnHeaders func(result map[string]any) error
	OnData    func(data []byte) error
	OnDone    func(result map[string]any) error
}

StreamOptions receives the upstream response synchronously on the calling goroutine.

type URLAction

type URLAction interface {
	GetURL() string
}

URLAction 定义显式指定 URL 的动作

type ValidatableAction

type ValidatableAction interface {
	Validate() error
}

ValidatableAction 定义支持自我校验的动作

Jump to

Keyboard shortcuts

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