proxy

package
v0.1.0 Latest Latest
Warning

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

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

Documentation

Index

Constants

This section is empty.

Variables

View Source
var BufferPool = newBufferPool()

全局 buffer pool(包级变量,禁止复制)

View Source
var RequestPluginRegistry = map[string]RequestPlugin{}

RequestPluginRegistry 请求插件注册表

View Source
var ResponsePluginRegistry = map[string]ResponsePlugin{}

ResponsePluginRegistry 响应插件注册表

Functions

func GetBuffer

func GetBuffer() *bytes.Buffer

GetBuffer 从全局池获取 buffer(便捷函数)

func NormalizeURL

func NormalizeURL(u string) string

NormalizeURL 移除 URL 中的默认端口 (https:443, http:80) 以提高匹配兼容性(优化版:带缓存)

func PutBuffer

func PutBuffer(buf *bytes.Buffer)

PutBuffer 归还 buffer 到全局池(便捷函数)

func RegisterPlugin

func RegisterPlugin(plugin RequestPlugin)

RegisterPlugin 注册一个请求插件

func RegisterResponsePlugin

func RegisterResponsePlugin(plugin ResponsePlugin)

RegisterResponsePlugin 注册一个响应插件

Types

type CertCache

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

CertCache 缓存 MITM 证书(LRU + TTL)

func NewCertCache

func NewCertCache(ttl time.Duration, maxSize int) *CertCache

NewCertCache 创建证书缓存

func (*CertCache) Get

func (c *CertCache) Get(host string) (*tls.Certificate, bool)

Get 从缓存获取证书

func (*CertCache) Set

func (c *CertCache) Set(host string, cert *tls.Certificate)

Set 设置证书到缓存

type ChatCompletionChunk

type ChatCompletionChunk struct {
	ID      string `json:"id"`
	Object  string `json:"object"`
	Created int64  `json:"created"`
	Model   string `json:"model"`
	Choices []struct {
		Index int `json:"index"`
		Delta struct {
			Role      string      `json:"role,omitempty"`
			Content   string      `json:"content,omitempty"`
			ToolCalls []ChunkTool `json:"tool_calls,omitempty"`
		} `json:"delta"`
		FinishReason *string `json:"finish_reason,omitempty"`
	} `json:"choices"`
	Usage map[string]interface{} `json:"usage,omitempty"`
}

ChatCompletionChunk 为 Chat Completion 流式响应块结构

type ChatCompletionRequest

type ChatCompletionRequest struct {
	Model               string              `json:"model"`
	Messages            []interface{}       `json:"messages"`
	ResponseFormat      *ChatResponseFormat `json:"response_format,omitempty"`
	Stream              bool                `json:"stream,omitempty"`
	MaxTokens           int                 `json:"max_tokens,omitempty"`
	MaxCompletionTokens int                 `json:"max_completion_tokens,omitempty"`
	Temperature         *float64            `json:"temperature,omitempty"`
	TopP                *float64            `json:"top_p,omitempty"`
	N                   *int                `json:"n,omitempty"`
	Tools               []interface{}       `json:"tools,omitempty"`
	ToolChoice          interface{}         `json:"tool_choice,omitempty"`
}

ChatCompletionRequest represents the standard OpenAI Chat Completion request

type ChatCompletionResponse

type ChatCompletionResponse struct {
	ID      string `json:"id"`
	Object  string `json:"object"`
	Created int64  `json:"created"`
	Model   string `json:"model"`
	Choices []struct {
		Index   int `json:"index"`
		Message struct {
			Role    string `json:"role"`
			Content string `json:"content"`
		} `json:"message"`
		FinishReason string `json:"finish_reason"`
	} `json:"choices"`
	Usage map[string]interface{} `json:"usage"`
}

定义一个非流式的 ChatCompletionResponse 用于 handleJSON

type ChatResponseFormat

type ChatResponseFormat struct {
	Type       string                 `json:"type"`
	JSONSchema map[string]interface{} `json:"json_schema,omitempty"`
}

type ChunkTool

type ChunkTool struct {
	Index    int    `json:"index"`
	ID       string `json:"id,omitempty"`
	Type     string `json:"type,omitempty"`
	Function struct {
		Name      string `json:"name,omitempty"`
		Arguments string `json:"arguments,omitempty"`
	} `json:"function"`
}

type CodexFixPlugin

type CodexFixPlugin struct {
	TargetModel string // 若不为空,则将请求中的 model 字段替换为此值
}

CodexFixPlugin 针对 Codex 客户端由于发出了包含对象数组的 messages 而导致的 validation errors 进行修复 它会将 messages 中的 content 对象数组拼接为纯文本字符串,并可选地替换 model 字段

func (*CodexFixPlugin) Name

func (c *CodexFixPlugin) Name() string

func (*CodexFixPlugin) ProcessRequest

func (c *CodexFixPlugin) ProcessRequest(req *http.Request) error

type Content

type Content struct {
	Type string `json:"type"`
	Text string `json:"text"`
}

type ContentPart

type ContentPart struct {
	Type  string `json:"type"`
	Index int    `json:"index"`
	Text  string `json:"text,omitempty"`
}

type HeaderRewriter

type HeaderRewriter struct {
	HeaderName  string
	HeaderValue string
	// contains filtered or unexported fields
}

HeaderRewriter 定义请求头重写器(优化版:预计算 key 和 value)

func NewHeaderRewriter

func NewHeaderRewriter(name, value string) *HeaderRewriter

NewHeaderRewriter 创建请求头重写器(优化版)

func (*HeaderRewriter) Rewrite

func (r *HeaderRewriter) Rewrite(req *http.Request)

Rewrite 重写 HTTP 请求头(优化版:直接使用预计算的 key 和 []byte)

type Item

type Item struct {
	ID        string    `json:"id"`
	Type      string    `json:"type"` // "message" or "function_call"
	Status    string    `json:"status,omitempty"`
	Role      string    `json:"role,omitempty"`
	Content   []Content `json:"content,omitempty"`
	Name      string    `json:"name,omitempty"`
	Arguments string    `json:"arguments,omitempty"`
	CallID    string    `json:"call_id,omitempty"`
}

type OpenAIResponsesPlugin

type OpenAIResponsesPlugin struct{}

OpenAIResponsesPlugin 将 OpenAI Chat Completions API 的响应转换为 Responses API 响应格式

func (*OpenAIResponsesPlugin) Name

func (p *OpenAIResponsesPlugin) Name() string

func (*OpenAIResponsesPlugin) ProcessRequest

func (p *OpenAIResponsesPlugin) ProcessRequest(req *http.Request) error

ProcessRequest 在请求发送前执行,确保上游返回明文以供插件处理

func (*OpenAIResponsesPlugin) ProcessResponse

func (p *OpenAIResponsesPlugin) ProcessResponse(resp *http.Response, ctx *goproxy.ProxyCtx, verbose bool) error

type ProxyRule

type ProxyRule struct {
	Name            string
	Matchers        []URLMatcher
	Rewriters       []*HeaderRewriter
	Plugins         []RequestPlugin
	ResponsePlugins []ResponsePlugin
}

ProxyRule 定义一组匹配规则及其对应的重写动作

type ProxyServer

type ProxyServer struct {
	Port          int
	UpstreamProxy string
	Rules         []*ProxyRule
	Verbose       bool
	DumpTraffic   bool
	Logger        *log.Logger
	// contains filtered or unexported fields
}

ProxyServer MITM 代理服务器

func NewProxyServer

func NewProxyServer(port int, upstream string, verbose bool, logger *log.Logger) *ProxyServer

NewProxyServer 创建新的代理服务器(优化版:带连接池)

func (*ProxyServer) AddMatcher

func (s *ProxyServer) AddMatcher(matcher URLMatcher)

AddMatcher 添加全局 URL 匹配器 (添加到默认规则)

func (*ProxyServer) AddPlugin

func (s *ProxyServer) AddPlugin(plugin RequestPlugin)

AddPlugin 添加请求插件 (添加到默认规则)

func (*ProxyServer) AddResponsePlugin

func (s *ProxyServer) AddResponsePlugin(plugin ResponsePlugin)

AddResponsePlugin 添加响应插件 (添加到默认规则)

func (*ProxyServer) AddRewriter

func (s *ProxyServer) AddRewriter(rewriter *HeaderRewriter)

AddRewriter 添加请求头重写器 (添加到默认规则)

func (*ProxyServer) AddRule

func (s *ProxyServer) AddRule(rule *ProxyRule)

AddRule 添加一个新的规则组

func (*ProxyServer) ShouldMITM

func (s *ProxyServer) ShouldMITM(host string) bool

ShouldMITM 判断是否需要对该 host 进行 MITM(优化版:O(1) 查找)

func (*ProxyServer) Start

func (s *ProxyServer) Start() error

Start 启动代理服务器

func (*ProxyServer) Stop

func (s *ProxyServer) Stop() error

Stop 停止代理服务器

type RegexMatcher

type RegexMatcher struct {
	Pattern *regexp.Regexp
}

RegexMatcher 使用正则表达式匹配 URL

func NewRegexMatcher

func NewRegexMatcher(pattern string) (*RegexMatcher, error)

NewRegexMatcher 创建正则表达式匹配器

func (*RegexMatcher) Match

func (m *RegexMatcher) Match(url string) bool

Match 检查 URL 是否匹配正则表达式

type RequestPlugin

type RequestPlugin interface {
	// Name 返回插件的名字,用于配置匹配
	Name() string
	// ProcessRequest 拦截并修改请求体。返回 error 则中断代理。
	ProcessRequest(req *http.Request) error
}

RequestPlugin 定义了一类可以在请求发送到上游前修改 *http.Request 的插件

func GetPlugin

func GetPlugin(fullName string) (RequestPlugin, error)

GetPlugin 根据名称获取插件实例,支持 "name:param" 格式

type ResponseFmt

type ResponseFmt struct {
	Type       string                 `json:"type"`
	JSONSchema map[string]interface{} `json:"json_schema,omitempty"`
}

type ResponsePlugin

type ResponsePlugin interface {
	// Name 返回插件的名字
	Name() string
	// ProcessResponse 拦截并修改响应体。返回 error 则中断代理。
	ProcessResponse(resp *http.Response, ctx *goproxy.ProxyCtx, verbose bool) error
}

ResponsePlugin 定义了一类可以在响应返回客户端前修改 *http.Response 的插件

func GetResponsePlugin

func GetResponsePlugin(fullName string) (ResponsePlugin, error)

GetResponsePlugin 根据名称获取响应插件实例

type ResponsesAPIEvent

type ResponsesAPIEvent struct {
	Type             string                `json:"type"`
	ResponseID       string                `json:"response_id,omitempty"`
	ItemID           string                `json:"item_id,omitempty"`
	Item             *Item                 `json:"item,omitempty"`
	ContentPart      *ContentPart          `json:"content_part,omitempty"`
	ContentPartIndex int                   `json:"content_part_index,omitempty"`
	Delta            string                `json:"delta,omitempty"`
	SequenceNumber   int                   `json:"sequence_number,omitempty"`
	OutputIndex      int                   `json:"output_index"`
	Usage            interface{}           `json:"usage,omitempty"`
	Response         *ResponsesAPIResponse `json:"response,omitempty"`
}

ResponsesAPIEvent 为 Responses API 流式事件结构

type ResponsesAPIPlugin

type ResponsesAPIPlugin struct{}

ResponsesAPIPlugin adapts the OpenAI Responses API (/v1/responses) to the Chat Completions API (/v1/chat/completions).

func (*ResponsesAPIPlugin) Name

func (p *ResponsesAPIPlugin) Name() string

func (*ResponsesAPIPlugin) ProcessRequest

func (p *ResponsesAPIPlugin) ProcessRequest(req *http.Request) error

func (*ResponsesAPIPlugin) ProcessResponse

func (p *ResponsesAPIPlugin) ProcessResponse(resp *http.Response, ctx *goproxy.ProxyCtx, verbose bool) error

type ResponsesAPIRequest

type ResponsesAPIRequest struct {
	Model           string        `json:"model"`
	Instructions    string        `json:"instructions,omitempty"`
	Input           []interface{} `json:"input,omitempty"`
	ResponseFormat  *ResponseFmt  `json:"response_format,omitempty"`
	Stream          bool          `json:"stream,omitempty"`
	MaxOutputTokens int           `json:"max_output_tokens,omitempty"`
	Temperature     *float64      `json:"temperature,omitempty"`
	TopP            *float64      `json:"top_p,omitempty"`
	N               *int          `json:"n,omitempty"`
	Tools           []interface{} `json:"tools,omitempty"`
	ToolChoice      interface{}   `json:"tool_choice,omitempty"`
}

ResponsesAPIRequest represents the incoming request body for /v1/responses

type ResponsesAPIResponse

type ResponsesAPIResponse struct {
	ID        string      `json:"id"`
	Object    string      `json:"object"`
	CreatedAt int64       `json:"created_at"`
	Model     string      `json:"model"`
	Output    []Item      `json:"output"`
	Usage     interface{} `json:"usage,omitempty"`
}

ResponsesAPIResponse 为 Responses API 响应结构

type StringMatcher

type StringMatcher struct {
	Pattern string
}

StringMatcher 使用字符串包含匹配 URL

func NewStringMatcher

func NewStringMatcher(pattern string) *StringMatcher

NewStringMatcher 创建字符串匹配器

func (*StringMatcher) Match

func (m *StringMatcher) Match(url string) bool

Match 检查 URL 是否包含指定字符串

type URLMatcher

type URLMatcher interface {
	Match(url string) bool
}

URLMatcher 定义 URL 匹配接口

Jump to

Keyboard shortcuts

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