- 分离 Request 的配置态与执行态,修复二次 Do、raw 模式网络配置失效和 body 来源互斥问题 - 新增 starnet trace 抽象,补齐 DNS/连接/TLS/重试事件,并优化动态 transport 缓存与代理解析路径 - 收紧非法代理为 fail-fast,多目标目标回退仅限幂等请求,修复 Host/TLS/SNI 等语义边界 - 补充防御性拷贝、专项回归测试、本地代理/TLS 用例与 README 行为说明
100 lines
2.1 KiB
Go
100 lines
2.1 KiB
Go
package starnet
|
||
|
||
import "net/http"
|
||
|
||
// WithHeader 设置 Header
|
||
func WithHeader(key, value string) RequestOpt {
|
||
return func(r *Request) error {
|
||
if isHostHeaderKey(key) {
|
||
setRequestHostConfig(r.config, value)
|
||
return nil
|
||
}
|
||
r.config.Headers.Set(key, value)
|
||
return nil
|
||
}
|
||
}
|
||
|
||
// WithHost 设置显式 Host 头覆盖。
|
||
func WithHost(host string) RequestOpt {
|
||
return func(r *Request) error {
|
||
setRequestHostConfig(r.config, host)
|
||
return nil
|
||
}
|
||
}
|
||
|
||
// WithHeaders 批量设置 Headers
|
||
func WithHeaders(headers map[string]string) RequestOpt {
|
||
return func(r *Request) error {
|
||
for key, value := range headers {
|
||
if isHostHeaderKey(key) {
|
||
setRequestHostConfig(r.config, value)
|
||
continue
|
||
}
|
||
r.config.Headers.Set(key, value)
|
||
}
|
||
return nil
|
||
}
|
||
}
|
||
|
||
// WithContentType 设置 Content-Type
|
||
func WithContentType(contentType string) RequestOpt {
|
||
return func(r *Request) error {
|
||
r.config.Headers.Set("Content-Type", contentType)
|
||
return nil
|
||
}
|
||
}
|
||
|
||
// WithUserAgent 设置 User-Agent
|
||
func WithUserAgent(userAgent string) RequestOpt {
|
||
return func(r *Request) error {
|
||
r.config.Headers.Set("User-Agent", userAgent)
|
||
return nil
|
||
}
|
||
}
|
||
|
||
// WithBearerToken 设置 Bearer Token
|
||
func WithBearerToken(token string) RequestOpt {
|
||
return func(r *Request) error {
|
||
r.config.Headers.Set("Authorization", "Bearer "+token)
|
||
return nil
|
||
}
|
||
}
|
||
|
||
// WithCookie 添加 Cookie
|
||
func WithCookie(name, value, path string) RequestOpt {
|
||
return func(r *Request) error {
|
||
r.config.Cookies = append(r.config.Cookies, &http.Cookie{
|
||
Name: name,
|
||
Value: value,
|
||
Path: path,
|
||
})
|
||
return nil
|
||
}
|
||
}
|
||
|
||
// WithSimpleCookie 添加简单 Cookie(path 为 /)
|
||
func WithSimpleCookie(name, value string) RequestOpt {
|
||
return func(r *Request) error {
|
||
r.config.Cookies = append(r.config.Cookies, &http.Cookie{
|
||
Name: name,
|
||
Value: value,
|
||
Path: "/",
|
||
})
|
||
return nil
|
||
}
|
||
}
|
||
|
||
// WithCookies 批量添加 Cookies
|
||
func WithCookies(cookies map[string]string) RequestOpt {
|
||
return func(r *Request) error {
|
||
for name, value := range cookies {
|
||
r.config.Cookies = append(r.config.Cookies, &http.Cookie{
|
||
Name: name,
|
||
Value: value,
|
||
Path: "/",
|
||
})
|
||
}
|
||
return nil
|
||
}
|
||
}
|