Documentation
¶
Overview ¶
Package channel 提供上游渠道的建模与 HTTP 客户端:基址拼接、鉴权样式、超时、 重试与 SSE 读写。
渠道只负责「怎么把一段字节送到上游、怎么把上游的字节读回来」,不解析协议内容: 方言之间的转换在 relay 包。
Index ¶
Constants ¶
View Source
const ( // StyleBearer 用 Authorization: Bearer <key>。 StyleBearer = "bearer" // StyleAPIKey 用 x-api-key: <key>。 StyleAPIKey = "x-api-key" // StyleQuery 把 key 放在查询参数上。 StyleQuery = "query" // StyleCustom 用指定名字的请求头。 StyleCustom = "custom" // StyleNone 不鉴权,用于指向本地假上游或已在内网放行的上游。 StyleNone = "none" )
鉴权样式的合法取值。
View Source
const DefaultMaxEventBytes = 8 << 20
DefaultMaxEventBytes 是单条 SSE 事件负载的默认上限。上游返回超长事件时按错误 处理,避免无上限地吃内存。
View Source
const DefaultTimeout = 120 * time.Second
DefaultTimeout 是未指定超时时的取值。
View Source
const MaxRetries = 10
MaxRetries 是重试次数的上限。转发是同步路径,重试次数乘以超时会直接变成 客户端等待时长,因此这里给一个上界而不是放任配置。
Variables ¶
View Source
var ErrEventTooLarge = errors.New("channel: 事件负载超过上限")
ErrEventTooLarge 表示单条事件超过上限。
View Source
var ErrMissingCredential = errors.New("channel: 凭据环境变量未设置")
ErrMissingCredential 表示凭据环境变量未设置。
Functions ¶
Types ¶
type Auth ¶
type Auth struct {
// Style 取 bearer、x-api-key、query、custom 或 none。
Style string
// KeyEnv 是凭据所在的环境变量名。凭据只在创建客户端时从进程环境读一次。
KeyEnv string
// Header 是 Style 为 custom 时的请求头名。
Header string
// Query 是 Style 为 query 时的查询参数名。
Query string
}
Auth 是渠道的鉴权方式。
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client 是一个渠道的 HTTP 客户端。可以并发使用。
type Event ¶
type Event struct {
// Name 是 event 字段,缺省为空。
Name string
// Data 是 data 字段拼接后的内容,末尾换行已去掉。
Data []byte
}
Event 是一条 SSE 事件。
type Reader ¶
type Reader struct {
// contains filtered or unexported fields
}
Reader 逐个读出 SSE 事件。
func (*Reader) Next ¶
Next 返回下一条事件。流结束时返回 io.EOF。
解析遵循 SSE 的常用子集:忽略注释行与未知字段;data 行按行拼接,行间补 \n; 空行分发事件;`data: [DONE]` 之类的结束标记原样返回,由调用方判断。
func (*Reader) SetMaxEventBytes ¶
SetMaxEventBytes 调整单条事件上限,非正数表示用默认值。
type Request ¶
type Request struct {
// Dialect 覆盖渠道的默认方言,用于同一条渠道上按路由切换协议。
// 为空时用渠道自己的方言。覆盖生效时渠道的 Path 不参与拼接,
// 因为那个值是按渠道方言写的。
Dialect dialect.Name
// Method 是 HTTP 方法,为空时用 POST。
Method string
// Model 是需要写进 URL 路径的模型名,只有 Gemini 用得到。
Model string
// Stream 决定取流式端点还是非流式端点,只有 Gemini 用得到。
Stream bool
// Body 是请求体,会被完整缓存在内存里,因此可以重试。
Body []byte
// Header 是附加请求头。
Header http.Header
}
Request 是一次上游调用。
type Spec ¶
type Spec struct {
Name string
// Dialect 是上游说话用的方言。
Dialect dialect.Name
// BaseURL 是渠道根地址,例如 https://api.openai.com。
BaseURL string
// Path 覆盖方言的默认上游路径。BaseURL 已带路径时(例如
// https://openrouter.ai/api/v1)必须显式给出,取值从该路径之后算起。
// Gemini 的路径含模型名,不允许覆盖。
Path string
// Auth 是鉴权方式。
Auth Auth
// Timeout 是单次请求的整体超时。为 0 时用 DefaultTimeout。
Timeout time.Duration
// MaxRetries 是失败后的重试次数,0 表示不重试。
MaxRetries int
// Headers 是附加到每个请求上的头。
Headers map[string]string
}
Spec 是一个渠道的完整描述。
Click to show internal directories.
Click to hide internal directories.