Documentation
¶
Index ¶
- Constants
- Variables
- func BuildPostForm(data map[string]string) []byte
- func BuildQuery(data map[string]string) string
- func DefaultHTTPClient() *http.Client
- func IsCanceled(err error) bool
- func IsDNS(err error) bool
- func IsIpPingable(ip string, timeout time.Duration, retryLimit int) bool
- func IsProxy(err error) bool
- func IsTLS(err error) bool
- func IsTimeout(err error) bool
- func Pingable(host string, opts *PingOptions) (bool, error)
- func SetDefaultClient(client *Client)
- func SetDefaultHTTPClient(client *http.Client)
- func TLSDefaults() *tls.Config
- func UrlDecode(str string) (string, error)
- func UrlEncode(str string) string
- func UrlEncodeRaw(str string) string
- type Body
- func (b *Body) Bytes() ([]byte, error)
- func (b *Body) Close() error
- func (b *Body) IsConsumed() bool
- func (b *Body) JSON(v interface{}) error
- func (b *Body) MustBytes() []byte
- func (b *Body) MustString() string
- func (b *Body) Reader() (io.ReadCloser, error)
- func (b *Body) String() (string, error)
- func (b *Body) Unmarshal(v interface{}) error
- type BodyConfig
- type Client
- func (c *Client) AddOptions(opts ...RequestOpt) *Client
- func (c *Client) Clone() *Client
- func (c *Client) Connect(url string, opts ...RequestOpt) (*Response, error)
- func (c *Client) Delete(url string, opts ...RequestOpt) (*Response, error)
- func (c *Client) DisableRedirect() *Client
- func (c *Client) EnableRedirect() *Client
- func (c *Client) Get(url string, opts ...RequestOpt) (*Response, error)
- func (c *Client) HTTPClient() *http.Client
- func (c *Client) Head(url string, opts ...RequestOpt) (*Response, error)
- func (c *Client) NewRequest(url, method string, opts ...RequestOpt) (*Request, error)
- func (c *Client) NewRequestWithContext(ctx context.Context, url, method string, opts ...RequestOpt) (*Request, error)
- func (c *Client) NewSimpleRequest(url, method string, opts ...RequestOpt) *Request
- func (c *Client) NewSimpleRequestWithContext(ctx context.Context, url, method string, opts ...RequestOpt) *Request
- func (c *Client) Options(url string, opts ...RequestOpt) (*Response, error)
- func (c *Client) Patch(url string, opts ...RequestOpt) (*Response, error)
- func (c *Client) Post(url string, opts ...RequestOpt) (*Response, error)
- func (c *Client) Put(url string, opts ...RequestOpt) (*Response, error)
- func (c *Client) RequestOptions() []RequestOpt
- func (c *Client) SetDefaultSkipTLSVerify(skip bool) *Client
- func (c *Client) SetDefaultTLSConfig(tlsConfig *tls.Config) *Client
- func (c *Client) SetOptions(opts ...RequestOpt) *Client
- func (c *Client) Trace(url string, opts ...RequestOpt) (*Response, error)
- type ClientHelloMeta
- type Conn
- func Dial(network, address string) (*Conn, error)
- func DialTLS(network, address, certFile, keyFile string) (*Conn, error)
- func DialTLSWithConfig(network, address string, tlsCfg *tls.Config, timeout time.Duration) (*Conn, error)
- func DialWithConfig(network, address string, dc DialConfig) (*Conn, error)
- func (c *Conn) ClientHello() *ClientHelloMeta
- func (c *Conn) Close() error
- func (c *Conn) Hostname() string
- func (c *Conn) IsTLS() bool
- func (c *Conn) Read(b []byte) (int, error)
- func (c *Conn) SetDeadline(t time.Time) error
- func (c *Conn) SetReadDeadline(t time.Time) error
- func (c *Conn) SetWriteDeadline(t time.Time) error
- func (c *Conn) TLSConn() (*tls.Conn, error)
- func (c *Conn) Write(b []byte) (int, error)
- type DNSConfig
- type DialConfig
- type ErrorKind
- type GetConfigForClientFunc
- type GetConfigForClientHelloFunc
- type ICMP
- type Listener
- func Listen(network, address string) (*Listener, error)
- func ListenTLS(network, address, certFile, keyFile string, allowNonTLS bool) (*Listener, error)
- func ListenWithConfig(network, address string, cfg ListenerConfig) (*Listener, error)
- func ListenWithListenConfig(lc net.ListenConfig, network, address string, cfg ListenerConfig) (*Listener, error)
- func WrapListener(listener net.Listener, cfg ListenerConfig) (*Listener, error)
- type ListenerConfig
- type Logger
- type NetworkConfig
- type PingOptions
- type PingResult
- type Request
- func NewRequest(url, method string, opts ...RequestOpt) (*Request, error)
- func NewRequestWithContext(ctx context.Context, url, method string, opts ...RequestOpt) (*Request, error)
- func NewSimpleRequest(url, method string, opts ...RequestOpt) *Request
- func NewSimpleRequestWithContext(ctx context.Context, url, method string, opts ...RequestOpt) *Request
- func (r *Request) AddCookie(cookie *http.Cookie) *Request
- func (r *Request) AddCookieKV(name, value, path string) *Request
- func (r *Request) AddCookies(cookies map[string]string) *Request
- func (r *Request) AddCustomDNS(dns string) *Request
- func (r *Request) AddCustomIP(ip string) *Request
- func (r *Request) AddFile(formName, filePath string) *Request
- func (r *Request) AddFileStream(formName, fileName string, size int64, reader io.Reader) *Request
- func (r *Request) AddFileStreamWithType(formName, fileName, fileType string, size int64, reader io.Reader) *Request
- func (r *Request) AddFileWithName(formName, filePath, fileName string) *Request
- func (r *Request) AddFileWithType(formName, filePath, fileType string) *Request
- func (r *Request) AddFormData(key, value string) *Request
- func (r *Request) AddFormDataMap(data map[string]string) *Request
- func (r *Request) AddHeader(key, value string) *Request
- func (r *Request) AddHeaders(headers map[string]string) *Request
- func (r *Request) AddQueries(queries map[string]string) *Request
- func (r *Request) AddQuery(key, value string) *Request
- func (r *Request) AddSimpleCookie(name, value string) *Request
- func (r *Request) Client() *Client
- func (r *Request) Clone() *Request
- func (r *Request) Connect() (*Response, error)
- func (r *Request) Context() context.Context
- func (r *Request) Cookies() []*http.Cookie
- func (r *Request) Delete() (*Response, error)
- func (r *Request) DeleteHeader(key string) *Request
- func (r *Request) DeleteQuery(key string) *Request
- func (r *Request) DeleteQueryValue(key, value string) *Request
- func (r *Request) DisableRawMode() *Request
- func (r *Request) DisableRetry() *Request
- func (r *Request) Do() (*Response, error)
- func (r *Request) EnableRawMode() *Request
- func (r *Request) Err() error
- func (r *Request) Get() (*Response, error)
- func (r *Request) GetHeader(key string) string
- func (r *Request) HTTPClient() (*http.Client, error)
- func (r *Request) Head() (*Response, error)
- func (r *Request) Headers() http.Header
- func (r *Request) Host() string
- func (r *Request) Method() string
- func (r *Request) Options() (*Response, error)
- func (r *Request) Patch() (*Response, error)
- func (r *Request) Post() (*Response, error)
- func (r *Request) Put() (*Response, error)
- func (r *Request) RawRequest() *http.Request
- func (r *Request) ResetCookies() *Request
- func (r *Request) ResetHeaders() *Request
- func (r *Request) SetAutoCalcContentLength(auto bool) *Request
- func (r *Request) SetAutoFetch(auto bool) *Request
- func (r *Request) SetBasicAuth(username, password string) *Request
- func (r *Request) SetBearerToken(token string) *Request
- func (r *Request) SetBody(body []byte) *Request
- func (r *Request) SetBodyReader(reader io.Reader) *Request
- func (r *Request) SetBodyString(body string) *Request
- func (r *Request) SetContentLength(length int64) *Request
- func (r *Request) SetContentType(contentType string) *Request
- func (r *Request) SetContext(ctx context.Context) *Request
- func (r *Request) SetCookies(cookies []*http.Cookie) *Request
- func (r *Request) SetCustomDNS(dnsServers []string) *Request
- func (r *Request) SetCustomIP(ips []string) *Request
- func (r *Request) SetDialFunc(fn func(ctx context.Context, network, addr string) (net.Conn, error)) *Request
- func (r *Request) SetDialTimeout(timeout time.Duration) *Request
- func (r *Request) SetFormData(data map[string][]string) *Request
- func (r *Request) SetHeader(key, value string) *Request
- func (r *Request) SetHeaders(headers http.Header) *Request
- func (r *Request) SetHost(host string) *Request
- func (r *Request) SetJSON(v interface{}) *Request
- func (r *Request) SetLookupFunc(fn func(ctx context.Context, host string) ([]net.IPAddr, error)) *Request
- func (r *Request) SetMaxRespBodyBytes(maxBytes int64) *Request
- func (r *Request) SetMethod(method string) *Request
- func (r *Request) SetProxy(proxy string) *Request
- func (r *Request) SetQueries(queries map[string][]string) *Request
- func (r *Request) SetQuery(key, value string) *Request
- func (r *Request) SetRawRequest(httpReq *http.Request) *Request
- func (r *Request) SetReferer(referer string) *Request
- func (r *Request) SetRetry(max int, opts ...RetryOpt) *Request
- func (r *Request) SetRetryBackoff(base, max time.Duration, factor float64) *Request
- func (r *Request) SetRetryIdempotentOnly(enabled bool) *Request
- func (r *Request) SetRetryJitter(ratio float64) *Request
- func (r *Request) SetRetryOnError(fn func(error) bool) *Request
- func (r *Request) SetRetryStatuses(codes ...int) *Request
- func (r *Request) SetSkipTLSVerify(skip bool) *Request
- func (r *Request) SetTLSConfig(tlsConfig *tls.Config) *Request
- func (r *Request) SetTLSServerName(serverName string) *Request
- func (r *Request) SetTimeout(timeout time.Duration) *Request
- func (r *Request) SetTraceHooks(hooks *TraceHooks) *Request
- func (r *Request) SetTraceRecorder(recorder *TraceRecorder) *Request
- func (r *Request) SetTransport(transport *http.Transport) *Request
- func (r *Request) SetURL(urlStr string) *Request
- func (r *Request) SetUploadProgress(fn UploadProgressFunc) *Request
- func (r *Request) SetUserAgent(userAgent string) *Request
- func (r *Request) Trace() (*Response, error)
- func (r *Request) TraceSummary() *TraceSummary
- func (r *Request) URL() string
- type RequestConfig
- type RequestContext
- type RequestFile
- type RequestOpt
- func WithAddCustomDNS(dns string) RequestOpt
- func WithAddCustomIP(ip string) RequestOpt
- func WithAddFormData(key, value string) RequestOpt
- func WithAutoCalcContentLength(auto bool) RequestOpt
- func WithAutoFetch(auto bool) RequestOpt
- func WithBasicAuth(username, password string) RequestOpt
- func WithBearerToken(token string) RequestOpt
- func WithBody(body []byte) RequestOpt
- func WithBodyReader(reader io.Reader) RequestOpt
- func WithBodyString(body string) RequestOpt
- func WithContentLength(length int64) RequestOpt
- func WithContentType(contentType string) RequestOpt
- func WithContext(ctx context.Context) RequestOpt
- func WithCookie(name, value, path string) RequestOpt
- func WithCookies(cookies map[string]string) RequestOpt
- func WithCustomDNS(dnsServers []string) RequestOpt
- func WithCustomIP(ips []string) RequestOpt
- func WithDialFunc(fn func(ctx context.Context, network, addr string) (net.Conn, error)) RequestOpt
- func WithDialTimeout(timeout time.Duration) RequestOpt
- func WithFile(formName, filePath string) RequestOpt
- func WithFileStream(formName, fileName string, size int64, reader io.Reader) RequestOpt
- func WithFormData(data map[string][]string) RequestOpt
- func WithFormDataMap(data map[string]string) RequestOpt
- func WithHeader(key, value string) RequestOpt
- func WithHeaders(headers map[string]string) RequestOpt
- func WithHost(host string) RequestOpt
- func WithJSON(v interface{}) RequestOpt
- func WithLookupFunc(fn func(ctx context.Context, host string) ([]net.IPAddr, error)) RequestOpt
- func WithMaxRespBodyBytes(maxBytes int64) RequestOpt
- func WithProxy(proxy string) RequestOpt
- func WithQueries(queries map[string]string) RequestOpt
- func WithQuery(key, value string) RequestOpt
- func WithRawRequest(httpReq *http.Request) RequestOpt
- func WithRetry(max int, opts ...RetryOpt) RequestOpt
- func WithSimpleCookie(name, value string) RequestOpt
- func WithSkipTLSVerify(skip bool) RequestOpt
- func WithTLSConfig(tlsConfig *tls.Config) RequestOpt
- func WithTLSServerName(serverName string) RequestOpt
- func WithTimeout(timeout time.Duration) RequestOpt
- func WithTraceHooks(hooks *TraceHooks) RequestOpt
- func WithTraceRecorder(recorder *TraceRecorder) RequestOpt
- func WithTransport(transport *http.Transport) RequestOpt
- func WithUploadProgress(fn UploadProgressFunc) RequestOpt
- func WithUserAgent(userAgent string) RequestOpt
- type Response
- func Connect(url string, opts ...RequestOpt) (*Response, error)
- func Delete(url string, opts ...RequestOpt) (*Response, error)
- func Get(url string, opts ...RequestOpt) (*Response, error)
- func Head(url string, opts ...RequestOpt) (*Response, error)
- func Options(url string, opts ...RequestOpt) (*Response, error)
- func Patch(url string, opts ...RequestOpt) (*Response, error)
- func Post(url string, opts ...RequestOpt) (*Response, error)
- func Put(url string, opts ...RequestOpt) (*Response, error)
- func Trace(url string, opts ...RequestOpt) (*Response, error)
- type RetryOpt
- type SniffResult
- type Sniffer
- type Stats
- type StatsSnapshot
- type TLSConfig
- type TLSSniffer
- type TraceCertificateSummary
- type TraceConnSummary
- type TraceConnectDoneInfo
- type TraceConnectStartInfo
- type TraceConnectSummary
- type TraceDNSDoneInfo
- type TraceDNSStartInfo
- type TraceDNSSummary
- type TraceGetConnInfo
- type TraceGotConnInfo
- type TraceHooks
- type TracePutIdleConnInfo
- type TraceRecorder
- type TraceRetryAttemptDoneInfo
- type TraceRetryAttemptStartInfo
- type TraceRetryBackoffInfo
- type TraceSummary
- type TraceTLSHandshakeDoneInfo
- type TraceTLSHandshakeStartInfo
- type TraceTLSSummary
- type TraceWroteHeaderFieldInfo
- type TraceWroteRequestInfo
- type Transport
- type UploadProgressFunc
Examples ¶
Constants ¶
const ( ContentTypeFormURLEncoded = "application/x-www-form-urlencoded" ContentTypeFormData = "multipart/form-data" ContentTypeJSON = "application/json" ContentTypeXML = "application/xml" ContentTypePlain = "text/plain" ContentTypeHTML = "text/html" ContentTypeOctetStream = "application/octet-stream" )
HTTP Content-Type 常量
const ( DefaultDialTimeout = 5 * time.Second DefaultTimeout = 10 * time.Second DefaultUserAgent = "starnet" DefaultFetchRespBody = false )
默认配置
Variables ¶
var ( // ErrInvalidMethod 无效的 HTTP 方法 ErrInvalidMethod = errors.New("starnet: invalid HTTP method") // ErrInvalidURL 无效的 URL ErrInvalidURL = errors.New("starnet: invalid URL") // ErrInvalidIP 无效的 IP 地址 ErrInvalidIP = errors.New("starnet: invalid IP address") // ErrInvalidDNS 无效的 DNS 服务器 ErrInvalidDNS = errors.New("starnet: invalid DNS server") // ErrNilClient HTTP Client 为 nil ErrNilClient = errors.New("starnet: http client is nil") // ErrNilReader Reader 为 nil ErrNilReader = errors.New("starnet: reader is nil") // ErrFileNotFound 文件不存在 ErrFileNotFound = errors.New("starnet: file not found") // ErrRequestNotPrepared 请求未准备好 ErrRequestNotPrepared = errors.New("starnet: request not prepared") // ErrBodyAlreadyConsumed Body 已被消费 ErrBodyAlreadyConsumed = errors.New("starnet: response body already consumed") // ErrRespBodyTooLarge 响应体超过允许上限 ErrRespBodyTooLarge = errors.New("starnet: response body too large") // ErrPingInvalidTimeout ping 超时参数无效 ErrPingInvalidTimeout = errors.New("starnet: invalid ping timeout") // ErrPingPermissionDenied ping 需要更高权限(raw socket) ErrPingPermissionDenied = errors.New("starnet: ping permission denied") // ErrPingProtocolUnsupported ping 协议/地址族不受当前平台支持 ErrPingProtocolUnsupported = errors.New("starnet: ping protocol unsupported") // ErrPingNoResolvedTarget ping 目标无法解析为可用地址 ErrPingNoResolvedTarget = errors.New("starnet: ping target not resolved") )
var ( // ErrNilConn indicates a nil net.Conn argument. ErrNilConn = errors.New("starnet: nil connection") // ErrTLSSniffFailed indicates TLS sniffing/parsing failed before handshake setup. ErrTLSSniffFailed = errors.New("starnet: tls sniff failed") // ErrTLSConfigSelectionFailed indicates dynamic TLS config selection failed. ErrTLSConfigSelectionFailed = errors.New("starnet: tls config selection failed") // ErrNonTLSNotAllowed indicates plain TCP was detected while non-TLS is forbidden. ErrNonTLSNotAllowed = errors.New("starnet: non-TLS connection not allowed") // ErrNotTLS indicates caller asked for TLS-only object but conn is plain TCP. ErrNotTLS = errors.New("starnet: connection is not TLS") // ErrNoTLSConfig indicates TLS was detected but no usable TLS config is available. ErrNoTLSConfig = errors.New("starnet: no TLS config available") )
Functions ¶
func DefaultHTTPClient ¶
DefaultHTTPClient 获取默认 http.Client(单例)
func IsCanceled ¶
IsCanceled reports whether err is a cancellation-related error.
func IsIpPingable ¶
IsIpPingable keeps backward-compatible bool-only behavior.
func Pingable ¶
func Pingable(host string, opts *PingOptions) (bool, error)
Pingable checks host reachability with retry options.
func SetDefaultHTTPClient ¶
SetDefaultHTTPClient 设置默认 http.Client
func TLSDefaults ¶
TLSDefaults returns a TLS config baseline. Caller should set Certificates / GetCertificate as needed.
Types ¶
type BodyConfig ¶
type BodyConfig struct {
Mode bodyMode // 当前 body 来源模式
Bytes []byte // 原始字节
Reader io.Reader // 数据流
FormData map[string][]string // 表单数据
Files []RequestFile // 文件列表
}
BodyConfig 请求体配置
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client HTTP 客户端封装
func NewClientFromHTTP ¶
NewClientFromHTTP 从 http.Client 创建 Client
func NewClientNoErr ¶
func NewClientNoErr(opts ...RequestOpt) *Client
NewClientNoErr 创建新的 Client(忽略错误)。 当 opts 校验失败时,它仍会返回一个可用的 Client 占位对象; 如果调用方需要感知选项错误或依赖默认 starnet Transport 行为,应优先使用 NewClient。
func (*Client) AddOptions ¶
func (c *Client) AddOptions(opts ...RequestOpt) *Client
AddOptions 追加默认选项
func (*Client) Connect ¶
func (c *Client) Connect(url string, opts ...RequestOpt) (*Response, error)
Connect 发送 CONNECT 请求
func (*Client) Delete ¶
func (c *Client) Delete(url string, opts ...RequestOpt) (*Response, error)
Delete 发送 DELETE 请求
func (*Client) Get ¶
func (c *Client) Get(url string, opts ...RequestOpt) (*Response, error)
Get 发送 GET 请求
Example ¶
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"time"
"b612.me/starnet"
)
func main() {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Client GET"))
}))
defer server.Close()
client := starnet.NewClientNoErr(
starnet.WithTimeout(10*time.Second),
starnet.WithUserAgent("MyApp/1.0"),
)
resp, err := client.Get(server.URL)
if err != nil {
panic(err)
}
defer resp.Close()
body, _ := resp.Body().String()
fmt.Println(body)
}
Output: Client GET
func (*Client) Head ¶
func (c *Client) Head(url string, opts ...RequestOpt) (*Response, error)
Head 发送 HEAD 请求
func (*Client) NewRequest ¶
func (c *Client) NewRequest(url, method string, opts ...RequestOpt) (*Request, error)
NewRequest 创建新请求
func (*Client) NewRequestWithContext ¶
func (c *Client) NewRequestWithContext(ctx context.Context, url, method string, opts ...RequestOpt) (*Request, error)
NewRequestWithContext 创建新请求(带 context)
func (*Client) NewSimpleRequest ¶
func (c *Client) NewSimpleRequest(url, method string, opts ...RequestOpt) *Request
NewSimpleRequest 创建新请求(忽略错误,支持链式调用)
func (*Client) NewSimpleRequestWithContext ¶
func (c *Client) NewSimpleRequestWithContext(ctx context.Context, url, method string, opts ...RequestOpt) *Request
NewSimpleRequestWithContext 创建新请求(带 context,忽略错误)
func (*Client) Options ¶
func (c *Client) Options(url string, opts ...RequestOpt) (*Response, error)
Options 发送 OPTIONS 请求
func (*Client) Patch ¶
func (c *Client) Patch(url string, opts ...RequestOpt) (*Response, error)
Patch 发送 PATCH 请求
func (*Client) Post ¶
func (c *Client) Post(url string, opts ...RequestOpt) (*Response, error)
Post 发送 POST 请求
func (*Client) Put ¶
func (c *Client) Put(url string, opts ...RequestOpt) (*Response, error)
Put 发送 PUT 请求
func (*Client) RequestOptions ¶
func (c *Client) RequestOptions() []RequestOpt
RequestOptions 获取默认选项(返回副本)
func (*Client) SetDefaultSkipTLSVerify ¶
SetDefaultSkipTLSVerify 设置默认跳过 TLS 验证
Example ¶
package main
import (
"fmt"
"b612.me/starnet"
)
func main() {
client := starnet.NewClientNoErr()
client.SetDefaultSkipTLSVerify(true)
// All requests from this client will skip TLS verification
// unless overridden at request level
fmt.Println("Client configured")
}
Output: Client configured
func (*Client) SetDefaultTLSConfig ¶
SetDefaultTLSConfig 设置默认 TLS 配置
func (*Client) SetOptions ¶
func (c *Client) SetOptions(opts ...RequestOpt) *Client
SetOptions 设置默认选项
type ClientHelloMeta ¶ added in v0.4.4
type ClientHelloMeta struct {
ServerName string
LocalAddr net.Addr
RemoteAddr net.Addr
SupportedProtos []string
SupportedVersions []uint16
CipherSuites []uint16
}
ClientHelloMeta carries sniffed TLS metadata and connection context.
func (*ClientHelloMeta) Clone ¶ added in v0.4.4
func (m *ClientHelloMeta) Clone() *ClientHelloMeta
Clone returns a detached copy safe for callers to mutate.
type Conn ¶
Conn wraps net.Conn with lazy protocol initialization.
func DialTLSWithConfig ¶
func DialTLSWithConfig(network, address string, tlsCfg *tls.Config, timeout time.Duration) (*Conn, error)
DialTLSWithConfig creates a TLS client connection wrapper.
func DialWithConfig ¶
func DialWithConfig(network, address string, dc DialConfig) (*Conn, error)
DialWithConfig dials with net.Dialer options.
func (*Conn) ClientHello ¶ added in v0.4.4
func (c *Conn) ClientHello() *ClientHelloMeta
ClientHello returns sniffed TLS metadata (if any).
type DNSConfig ¶
type DNSConfig struct {
CustomIP []string // 直接指定 IP(最高优先级)
CustomDNS []string // 自定义 DNS 服务器
LookupFunc func(ctx context.Context, host string) ([]net.IPAddr, error) // 自定义解析函数
}
DNSConfig DNS 配置
type DialConfig ¶
DialConfig controls dialing behavior.
type ErrorKind ¶
type ErrorKind string
ErrorKind is a normalized high-level category for request errors.
func ClassifyError ¶
ClassifyError maps low-level errors to a stable category for business handling.
type GetConfigForClientFunc ¶
GetConfigForClientFunc selects TLS config by hostname/SNI.
type GetConfigForClientHelloFunc ¶ added in v0.4.4
type GetConfigForClientHelloFunc func(hello *ClientHelloMeta) (*tls.Config, error)
GetConfigForClientHelloFunc selects TLS config by sniffed TLS metadata.
type Listener ¶
Listener wraps net.Listener and returns starnet.Conn from Accept.
func ListenWithConfig ¶
func ListenWithConfig(network, address string, cfg ListenerConfig) (*Listener, error)
ListenWithConfig creates a listener with full config.
func ListenWithListenConfig ¶
func ListenWithListenConfig(lc net.ListenConfig, network, address string, cfg ListenerConfig) (*Listener, error)
ListenWithListenConfig creates listener using net.ListenConfig.
func WrapListener ¶
func WrapListener(listener net.Listener, cfg ListenerConfig) (*Listener, error)
func (*Listener) AcceptContext ¶
AcceptContext supports cancellation by closing accepted conn when ctx is done early.
func (*Listener) Config ¶
func (l *Listener) Config() ListenerConfig
Config returns a copy of current config.
func (*Listener) SetConfig ¶
func (l *Listener) SetConfig(cfg ListenerConfig)
SetConfig atomically replaces listener config for new accepted connections.
func (*Listener) Stats ¶
func (l *Listener) Stats() StatsSnapshot
Stats returns current counters snapshot.
type ListenerConfig ¶
type ListenerConfig struct {
// BaseTLSConfig is used for TLS when dynamic selection returns nil.
BaseTLSConfig *tls.Config
// GetConfigForClient selects TLS config for a hostname/SNI.
// Deprecated: prefer GetConfigForClientHello for richer context.
GetConfigForClient GetConfigForClientFunc
// GetConfigForClientHello selects TLS config for sniffed TLS metadata.
GetConfigForClientHello GetConfigForClientHelloFunc
// AllowNonTLS allows plain TCP fallback.
AllowNonTLS bool
// SniffTimeout bounds protocol sniffing time. 0 means no timeout.
SniffTimeout time.Duration
// MaxClientHelloBytes limits buffered sniff data.
// If <= 0, default 64KiB.
MaxClientHelloBytes int
// Logger is optional.
Logger Logger
}
ListenerConfig controls listener behavior.
func DefaultListenerConfig ¶
func DefaultListenerConfig() ListenerConfig
DefaultListenerConfig returns a conservative default config.
type Logger ¶
type Logger interface {
Printf(format string, v ...interface{})
}
Logger is a minimal logging abstraction.
type NetworkConfig ¶
type NetworkConfig struct {
Proxy string // 代理地址
DialTimeout time.Duration // 连接超时
Timeout time.Duration // 总超时
DialFunc func(ctx context.Context, network, addr string) (net.Conn, error)
}
NetworkConfig 网络配置
type PingResult ¶
func PingWithContext ¶
func PingWithContext(ctx context.Context, host string, seq int, timeout time.Duration) (PingResult, error)
PingWithContext sends one ICMP echo request with context cancel support.
type Request ¶
type Request struct {
// contains filtered or unexported fields
}
Request HTTP 请求
func NewRequest ¶
func NewRequest(url, method string, opts ...RequestOpt) (*Request, error)
NewRequest 创建新请求
func NewRequestWithContext ¶
func NewRequestWithContext(ctx context.Context, url, method string, opts ...RequestOpt) (*Request, error)
NewRequestWithContext 创建新请求(带 context)
func NewSimpleRequest ¶
func NewSimpleRequest(url, method string, opts ...RequestOpt) *Request
NewSimpleRequest 创建新请求(忽略错误,支持链式调用)
Example ¶
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"b612.me/starnet"
)
func main() {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("OK"))
}))
defer server.Close()
req := starnet.NewSimpleRequest(server.URL, "GET").
SetHeader("X-Custom", "value").
AddQuery("name", "test")
resp, err := req.Do()
if err != nil {
panic(err)
}
defer resp.Close()
fmt.Println(resp.StatusCode)
}
Output: 200
func NewSimpleRequestWithContext ¶
func NewSimpleRequestWithContext(ctx context.Context, url, method string, opts ...RequestOpt) *Request
NewSimpleRequestWithContext 创建新请求(带 context,忽略错误)
func (*Request) AddCookieKV ¶
AddCookieKV 添加 Cookie(指定 path)
func (*Request) AddCookies ¶
AddCookies 批量添加 Cookies
func (*Request) AddCustomDNS ¶
AddCustomDNS 添加自定义 DNS 服务器
func (*Request) AddCustomIP ¶
AddCustomIP 添加自定义 IP
func (*Request) AddFileStream ¶
AddFileStream 添加文件流
func (*Request) AddFileStreamWithType ¶
func (r *Request) AddFileStreamWithType(formName, fileName, fileType string, size int64, reader io.Reader) *Request
AddFileStreamWithType 添加文件流(指定 MIME 类型)
func (*Request) AddFileWithName ¶
AddFileWithName 添加文件(指定文件名)
func (*Request) AddFileWithType ¶
AddFileWithType 添加文件(指定 MIME 类型)
func (*Request) AddFormData ¶
AddFormData 添加表单数据
Example ¶
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"b612.me/starnet"
)
func main() {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
fmt.Fprintf(w, "name=%s", r.FormValue("name"))
}))
defer server.Close()
resp, err := starnet.NewSimpleRequest(server.URL, "POST").
AddFormData("name", "John").
AddFormData("age", "30").
Do()
if err != nil {
panic(err)
}
defer resp.Close()
body, _ := resp.Body().String()
fmt.Println(body)
}
Output: name=John
func (*Request) AddFormDataMap ¶
AddFormDataMap 批量添加表单数据
func (*Request) AddHeaders ¶
AddHeaders 批量添加 Headers
func (*Request) AddQueries ¶
AddQueries 批量添加查询参数
func (*Request) AddSimpleCookie ¶
AddSimpleCookie 添加简单 Cookie(path 为 /)
func (*Request) Clone ¶
Clone 克隆请求
Example ¶
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"b612.me/starnet"
)
func main() {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("OK"))
}))
defer server.Close()
baseReq := starnet.NewSimpleRequest(server.URL, "GET").
SetHeader("X-API-Key", "secret")
// Clone and modify
req1 := baseReq.Clone().AddQuery("page", "1")
req2 := baseReq.Clone().AddQuery("page", "2")
resp1, _ := req1.Do()
resp2, _ := req2.Do()
defer resp1.Close()
defer resp2.Close()
fmt.Println(resp1.StatusCode, resp2.StatusCode)
}
Output: 200 200
func (*Request) DeleteHeader ¶
DeleteHeader 删除 Header
func (*Request) DeleteQueryValue ¶
DeleteQueryValue 删除查询参数的特定值
func (*Request) DisableRetry ¶
func (*Request) EnableRawMode ¶
EnableRawMode 启用原始模式(不修改请求)
func (*Request) HTTPClient ¶
HTTPClient 获取底层 http.Client(只读)
func (*Request) RawRequest ¶
RawRequest 获取底层 http.Request
func (*Request) SetAutoCalcContentLength ¶
SetAutoCalcContentLength 设置是否自动计算 Content-Length 警告:启用后会将整个 body 读入内存
func (*Request) SetAutoFetch ¶
SetAutoFetch 设置是否自动获取响应体
func (*Request) SetBasicAuth ¶
SetBasicAuth 设置 Basic 认证
func (*Request) SetBearerToken ¶
SetBearerToken 设置 Bearer Token
func (*Request) SetBodyReader ¶
SetBodyReader 设置请求体(Reader)。 出于避免重复写的保守策略,Reader 形态的 body 在非幂等方法上不会自动参与 retry。
func (*Request) SetBodyString ¶
SetBodyString 设置请求体(字符串)
func (*Request) SetContentLength ¶
SetContentLength 设置 Content-Length
func (*Request) SetContentType ¶
SetContentType 设置 Content-Type
func (*Request) SetContext ¶
SetContext 设置 context
func (*Request) SetCookies ¶
SetCookies 设置所有 Cookies(覆盖)
func (*Request) SetCustomDNS ¶
SetCustomDNS 设置自定义 DNS 服务器
func (*Request) SetCustomIP ¶
SetCustomIP 设置自定义 IP(直接指定 IP,跳过 DNS)
func (*Request) SetDialFunc ¶
func (r *Request) SetDialFunc(fn func(ctx context.Context, network, addr string) (net.Conn, error)) *Request
SetDialFunc 设置自定义 Dial 函数
func (*Request) SetDialTimeout ¶
SetDialTimeout 设置连接超时时间
func (*Request) SetFormData ¶
SetFormData 设置表单数据(覆盖)
func (*Request) SetHeaders ¶
SetHeaders 设置所有 Headers(覆盖)
func (*Request) SetJSON ¶
SetJSON 设置 JSON 请求体
Example ¶
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"b612.me/starnet"
)
func main() {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"status":"ok"}`))
}))
defer server.Close()
type User struct {
Name string `json:"name"`
Email string `json:"email"`
}
user := User{Name: "John", Email: "john@example.com"}
resp, err := starnet.NewSimpleRequest(server.URL, "POST").
SetJSON(user).
Do()
if err != nil {
panic(err)
}
defer resp.Close()
var result map[string]string
resp.Body().JSON(&result)
fmt.Println(result["status"])
}
Output: ok
func (*Request) SetLookupFunc ¶
func (r *Request) SetLookupFunc(fn func(ctx context.Context, host string) ([]net.IPAddr, error)) *Request
SetLookupFunc 设置自定义 DNS 解析函数
func (*Request) SetMaxRespBodyBytes ¶
SetMaxRespBodyBytes 设置响应体最大读取字节数(<=0 表示不限制)
func (*Request) SetQueries ¶
SetQueries 设置所有查询参数(覆盖)
func (*Request) SetRawRequest ¶
SetRawRequest 设置底层 http.Request(启用原始模式)
func (*Request) SetReferer ¶
SetReferer 设置 Referer
func (*Request) SetRetry ¶
SetRetry 为请求启用自动重试。 默认只重试幂等方法;即使显式关闭幂等限制,Reader 形态的 body 仍会对非幂等方法保持保守禁用, 以避免请求体已落地后再次发送。
Example ¶
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"sync/atomic"
"b612.me/starnet"
)
func main() {
var hits int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
n := atomic.AddInt32(&hits, 1)
if n == 1 {
w.WriteHeader(http.StatusServiceUnavailable)
return
}
w.WriteHeader(http.StatusOK)
}))
defer server.Close()
resp, err := starnet.NewSimpleRequest(server.URL, http.MethodPost).
SetBodyString("hello"). // 可重放 body 才能安全重试
SetRetry(1).
SetRetryIdempotentOnly(false).
SetRetryBackoff(0, 0, 1).
SetRetryJitter(0).
Do()
if err != nil {
panic(err)
}
defer resp.Close()
fmt.Println(resp.StatusCode, atomic.LoadInt32(&hits))
}
Output: 200 2
func (*Request) SetRetryBackoff ¶
func (*Request) SetRetryIdempotentOnly ¶
func (*Request) SetRetryJitter ¶
func (*Request) SetRetryStatuses ¶
func (*Request) SetSkipTLSVerify ¶
SetSkipTLSVerify 设置是否跳过 TLS 验证
Example ¶
package main
import (
"fmt"
"b612.me/starnet"
)
func main() {
// This example shows how to skip TLS verification
// Useful for testing with self-signed certificates
req := starnet.NewSimpleRequest("https://self-signed.example.com", "GET").
SetSkipTLSVerify(true)
// In a real scenario, you would call req.Do()
fmt.Println(req.Method())
}
Output: GET
func (*Request) SetTLSConfig ¶
SetTLSConfig 设置 TLS 配置
func (*Request) SetTLSServerName ¶ added in v0.5.0
SetTLSServerName 设置显式 TLS ServerName/SNI。
func (*Request) SetTimeout ¶
SetTimeout 设置请求总超时时间 timeout > 0: 为本次请求注入 context 超时 timeout = 0: 不额外设置请求总超时 timeout < 0: 禁用 starnet 默认总超时
func (*Request) SetTraceHooks ¶ added in v0.5.0
func (r *Request) SetTraceHooks(hooks *TraceHooks) *Request
SetTraceHooks 设置请求 trace 回调。
func (*Request) SetTraceRecorder ¶ added in v0.5.0
func (r *Request) SetTraceRecorder(recorder *TraceRecorder) *Request
SetTraceRecorder 设置请求级 trace 摘要记录器。 记录器会保存最近一次已完成请求的摘要;若多个请求共享同一个记录器,则以最后一次完成的请求为准。
func (*Request) SetTransport ¶
SetTransport 设置自定义 Transport
func (*Request) SetUploadProgress ¶
func (r *Request) SetUploadProgress(fn UploadProgressFunc) *Request
SetUploadProgress 设置文件上传进度回调
func (*Request) SetUserAgent ¶
SetUserAgent 设置 User-Agent
func (*Request) TraceSummary ¶ added in v0.5.0
func (r *Request) TraceSummary() *TraceSummary
TraceSummary 返回当前请求最近一次执行的 trace 摘要快照。
type RequestConfig ¶
type RequestConfig struct {
Network NetworkConfig
TLS TLSConfig
DNS DNSConfig
Body BodyConfig
Headers http.Header
Cookies []*http.Cookie
Queries map[string][]string
// 其他配置
BasicAuth [2]string // Basic 认证
Host string // 显式 Host 头覆盖
ContentLength int64 // 手动设置的 Content-Length
AutoCalcContentLength bool // 自动计算 Content-Length
MaxRespBodyBytes int64 // 响应体最大读取字节数(<=0 表示不限制)
UploadProgress UploadProgressFunc // 上传进度回调
// Transport 配置
CustomTransport bool // 是否使用自定义 Transport
Transport *http.Transport // 自定义 Transport
}
RequestConfig 请求配置(内部使用)
type RequestContext ¶
type RequestContext struct {
Transport *http.Transport
TLSConfig *tls.Config
TLSConfigCacheable bool
TLSServerName string
Proxy string
CustomIP []string
CustomDNS []string
DialTimeout time.Duration
Timeout time.Duration
LookupIPFn func(ctx context.Context, host string) ([]net.IPAddr, error)
DialFn func(ctx context.Context, network, addr string) (net.Conn, error)
}
RequestContext 从 context 中提取的请求配置
type RequestFile ¶
type RequestFile struct {
FormName string // 表单字段名
FileName string // 文件名
FilePath string // 文件路径(如果从文件读取)
FileData io.Reader // 文件数据流
FileSize int64 // 文件大小
FileType string // MIME 类型
}
RequestFile 表示要上传的文件
type RequestOpt ¶
RequestOpt 请求选项函数
func WithAutoCalcContentLength ¶
func WithAutoCalcContentLength(auto bool) RequestOpt
WithAutoCalcContentLength 设置是否自动计算 Content-Length
func WithBasicAuth ¶
func WithBasicAuth(username, password string) RequestOpt
WithBasicAuth 设置 Basic 认证
func WithBearerToken ¶
func WithBearerToken(token string) RequestOpt
WithBearerToken 设置 Bearer Token
func WithBodyReader ¶
func WithBodyReader(reader io.Reader) RequestOpt
WithBodyReader 设置请求体(Reader)。 出于避免重复写的保守策略,Reader 形态的 body 在非幂等方法上不会自动参与 retry。
func WithContentLength ¶
func WithContentLength(length int64) RequestOpt
WithContentLength 设置 Content-Length
func WithContentType ¶
func WithContentType(contentType string) RequestOpt
WithContentType 设置 Content-Type
func WithDialFunc ¶
WithDialFunc 设置自定义 Dial 函数
func WithDialTimeout ¶
func WithDialTimeout(timeout time.Duration) RequestOpt
WithDialTimeout 设置连接超时时间
func WithFileStream ¶
func WithFileStream(formName, fileName string, size int64, reader io.Reader) RequestOpt
WithFileStream 添加文件流
func WithFormDataMap ¶
func WithFormDataMap(data map[string]string) RequestOpt
WithFormDataMap 设置表单数据(简化版)
func WithLookupFunc ¶
WithLookupFunc 设置自定义 DNS 解析函数
func WithMaxRespBodyBytes ¶
func WithMaxRespBodyBytes(maxBytes int64) RequestOpt
WithMaxRespBodyBytes 设置响应体最大读取字节数(<=0 表示不限制)
func WithRetry ¶
func WithRetry(max int, opts ...RetryOpt) RequestOpt
WithRetry 为请求启用自动重试。 默认只重试幂等方法;即使显式关闭幂等限制,Reader 形态的 body 仍会对非幂等方法保持保守禁用, 以避免请求体已落地后再次发送。
Example ¶
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"sync/atomic"
"b612.me/starnet"
)
func main() {
var hits int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
n := atomic.AddInt32(&hits, 1)
if n <= 2 {
w.WriteHeader(http.StatusServiceUnavailable)
return
}
w.WriteHeader(http.StatusOK)
}))
defer server.Close()
resp, err := starnet.Get(server.URL,
starnet.WithRetry(2,
starnet.WithRetryBackoff(0, 0, 1),
starnet.WithRetryJitter(0),
),
)
if err != nil {
panic(err)
}
defer resp.Close()
fmt.Println(resp.StatusCode, atomic.LoadInt32(&hits))
}
Output: 200 3
func WithSimpleCookie ¶
func WithSimpleCookie(name, value string) RequestOpt
WithSimpleCookie 添加简单 Cookie(path 为 /)
func WithSkipTLSVerify ¶
func WithSkipTLSVerify(skip bool) RequestOpt
WithSkipTLSVerify 设置是否跳过 TLS 验证
func WithTLSServerName ¶ added in v0.5.0
func WithTLSServerName(serverName string) RequestOpt
WithTLSServerName 设置显式 TLS ServerName/SNI。
func WithTimeout ¶
func WithTimeout(timeout time.Duration) RequestOpt
WithTimeout 设置请求总超时时间 timeout > 0: 为本次请求注入 context 超时 timeout = 0: 不额外设置请求总超时 timeout < 0: 禁用 starnet 默认总超时
Example ¶
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"time"
"b612.me/starnet"
)
func main() {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(100 * time.Millisecond)
w.Write([]byte("OK"))
}))
defer server.Close()
resp, err := starnet.Get(server.URL,
starnet.WithTimeout(200*time.Millisecond))
if err != nil {
panic(err)
}
defer resp.Close()
fmt.Println(resp.StatusCode)
}
Output: 200
func WithTraceHooks ¶ added in v0.5.0
func WithTraceHooks(hooks *TraceHooks) RequestOpt
WithTraceHooks 设置请求 trace 回调。
func WithTraceRecorder ¶ added in v0.5.0
func WithTraceRecorder(recorder *TraceRecorder) RequestOpt
WithTraceRecorder 设置请求级 trace 摘要记录器。
func WithTransport ¶
func WithTransport(transport *http.Transport) RequestOpt
WithTransport 设置自定义 Transport
func WithUploadProgress ¶
func WithUploadProgress(fn UploadProgressFunc) RequestOpt
WithUploadProgress 设置文件上传进度回调
type Response ¶
Response HTTP 响应
func Connect ¶
func Connect(url string, opts ...RequestOpt) (*Response, error)
Connect 发送 CONNECT 请求(使用默认 Client)
func Delete ¶
func Delete(url string, opts ...RequestOpt) (*Response, error)
Delete 发送 DELETE 请求(使用默认 Client)
func Get ¶
func Get(url string, opts ...RequestOpt) (*Response, error)
Get 发送 GET 请求(使用默认 Client)
Example ¶
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"b612.me/starnet"
)
func main() {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello, World!"))
}))
defer server.Close()
resp, err := starnet.Get(server.URL)
if err != nil {
panic(err)
}
defer resp.Close()
body, _ := resp.Body().String()
fmt.Println(body)
}
Output: Hello, World!
func Head ¶
func Head(url string, opts ...RequestOpt) (*Response, error)
Head 发送 HEAD 请求(使用默认 Client)
func Options ¶
func Options(url string, opts ...RequestOpt) (*Response, error)
Options 发送 OPTIONS 请求(使用默认 Client)
func Patch ¶
func Patch(url string, opts ...RequestOpt) (*Response, error)
Patch 发送 PATCH 请求(使用默认 Client)
func Post ¶
func Post(url string, opts ...RequestOpt) (*Response, error)
Post 发送 POST 请求(使用默认 Client)
Example ¶
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"b612.me/starnet"
)
func main() {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Posted"))
}))
defer server.Close()
resp, err := starnet.Post(server.URL,
starnet.WithBodyString("test data"))
if err != nil {
panic(err)
}
defer resp.Close()
body, _ := resp.Body().String()
fmt.Println(body)
}
Output: Posted
func Trace ¶
func Trace(url string, opts ...RequestOpt) (*Response, error)
Trace 发送 TRACE 请求(使用默认 Client)
func (*Response) CloseWithClient ¶
CloseWithClient 关闭响应体并关闭空闲连接
func (*Response) TraceSummary ¶ added in v0.5.0
func (r *Response) TraceSummary() *TraceSummary
TraceSummary 获取当前响应对应的 trace 摘要快照。
type RetryOpt ¶
type RetryOpt func(*retryPolicy) error
func WithRetryIdempotentOnly ¶
func WithRetryJitter ¶
func WithRetryOnError ¶
func WithRetryStatuses ¶
type SniffResult ¶
type SniffResult struct {
IsTLS bool
ClientHello *ClientHelloMeta
Buffer *bytes.Buffer
}
SniffResult describes protocol sniffing result.
type Sniffer ¶
type Sniffer interface {
Sniff(conn net.Conn, maxBytes int) (SniffResult, error)
}
Sniffer detects protocol and metadata from initial bytes.
type Stats ¶
type Stats struct {
// contains filtered or unexported fields
}
Stats provides lock-free counters.
func (*Stats) Snapshot ¶
func (s *Stats) Snapshot() StatsSnapshot
Snapshot returns a stable view of counters.
type StatsSnapshot ¶
type StatsSnapshot struct {
Accepted uint64
TLSDetected uint64
PlainDetected uint64
InitFailures uint64
SniffFailures uint64
TLSConfigFailures uint64
PlainRejected uint64
Closed uint64
}
StatsSnapshot is a read-only copy of runtime counters.
type TLSConfig ¶
type TLSConfig struct {
Config *tls.Config // TLS 配置
SkipVerify bool // 跳过证书验证
ServerName string // 显式 TLS ServerName/SNI 覆盖
}
TLSConfig TLS 配置
type TLSSniffer ¶
type TLSSniffer struct{}
TLSSniffer is the default sniffer implementation.
func (TLSSniffer) Sniff ¶
func (s TLSSniffer) Sniff(conn net.Conn, maxBytes int) (SniffResult, error)
Sniff detects TLS and extracts SNI when possible.
type TraceCertificateSummary ¶ added in v0.5.0
type TraceCertificateSummary struct {
Subject string
Issuer string
DNSNames []string
IPAddresses []string
}
TraceCertificateSummary 是单张证书的关键信息摘要。
type TraceConnSummary ¶ added in v0.5.0
type TraceConnSummary struct {
Addr string
LocalAddr string
RemoteAddr string
Reused bool
WasIdle bool
IdleTime time.Duration
}
TraceConnSummary 是连接复用与套接字信息摘要。
type TraceConnectDoneInfo ¶ added in v0.5.0
type TraceConnectStartInfo ¶ added in v0.5.0
type TraceConnectSummary ¶ added in v0.5.0
type TraceConnectSummary struct {
Network string
Addr string
StartedAt time.Time
CompletedAt time.Time
Duration time.Duration
Err error
}
TraceConnectSummary 是单次建连尝试摘要。
type TraceDNSDoneInfo ¶ added in v0.5.0
type TraceDNSStartInfo ¶ added in v0.5.0
type TraceDNSStartInfo struct {
Host string
}
type TraceDNSSummary ¶ added in v0.5.0
type TraceDNSSummary struct {
Host string
Addrs []string
Coalesced bool
StartedAt time.Time
CompletedAt time.Time
Duration time.Duration
Err error
}
TraceDNSSummary 是 DNS 解析摘要。
type TraceGetConnInfo ¶ added in v0.5.0
type TraceGetConnInfo struct {
Addr string
}
type TraceGotConnInfo ¶ added in v0.5.0
type TraceHooks ¶ added in v0.5.0
type TraceHooks struct {
GetConn func(TraceGetConnInfo)
GotConn func(TraceGotConnInfo)
PutIdleConn func(TracePutIdleConnInfo)
DNSStart func(TraceDNSStartInfo)
DNSDone func(TraceDNSDoneInfo)
ConnectStart func(TraceConnectStartInfo)
ConnectDone func(TraceConnectDoneInfo)
TLSHandshakeStart func(TraceTLSHandshakeStartInfo)
TLSHandshakeDone func(TraceTLSHandshakeDoneInfo)
WroteHeaderField func(TraceWroteHeaderFieldInfo)
WroteHeaders func()
WroteRequest func(TraceWroteRequestInfo)
GotFirstResponseByte func()
RetryAttemptStart func(TraceRetryAttemptStartInfo)
RetryAttemptDone func(TraceRetryAttemptDoneInfo)
RetryBackoff func(TraceRetryBackoffInfo)
}
TraceHooks defines optional callbacks for network lifecycle events. Hooks may be called concurrently.
type TracePutIdleConnInfo ¶ added in v0.5.0
type TracePutIdleConnInfo struct {
Err error
}
type TraceRecorder ¶ added in v0.5.0
type TraceRecorder struct {
// contains filtered or unexported fields
}
TraceRecorder 聚合最近一次发布的 trace 摘要。 通过 Request/Client 绑定时,starnet 会为每次执行创建私有运行态并在完成后发布摘要; 直接使用 Hooks() 时,调用方仍需自行管理 Reset 与生命周期。
func NewTraceRecorder ¶ added in v0.5.0
func NewTraceRecorder() *TraceRecorder
NewTraceRecorder 创建请求级 trace 记录器。
func (*TraceRecorder) Hooks ¶ added in v0.5.0
func (r *TraceRecorder) Hooks() *TraceHooks
Hooks 返回可挂到请求上的底层 trace hooks。
func (*TraceRecorder) Summary ¶ added in v0.5.0
func (r *TraceRecorder) Summary() TraceSummary
Summary 返回当前 trace 摘要的快照。
type TraceRetryAttemptDoneInfo ¶ added in v0.5.0
type TraceRetryAttemptStartInfo ¶ added in v0.5.0
type TraceRetryBackoffInfo ¶ added in v0.5.0
type TraceSummary ¶ added in v0.5.0
type TraceSummary struct {
Method string
URL string
StartedAt time.Time
ResponseAt time.Time
StatusCode int
ResponseProto string
Conn TraceConnSummary
DNS *TraceDNSSummary
DNSEvents []TraceDNSSummary
Connect []TraceConnectSummary
TLS *TraceTLSSummary
RequestWrittenAt time.Time
RequestWriteErr error
FirstResponseByteAt time.Time
}
TraceSummary 是一次请求执行的 trace 摘要。
type TraceTLSHandshakeDoneInfo ¶ added in v0.5.0
type TraceTLSHandshakeStartInfo ¶ added in v0.5.0
type TraceTLSSummary ¶ added in v0.5.0
type TraceTLSSummary struct {
Network string
Addr string
ServerName string
Version uint16
VersionName string
CipherSuite uint16
CipherSuiteName string
CurveID tls.CurveID
CurveName string
NegotiatedProtocol string
DidResume bool
ECHAccepted bool
VerifiedChains int
StartedAt time.Time
CompletedAt time.Time
Duration time.Duration
Err error
PeerCertificates []TraceCertificateSummary
}
TraceTLSSummary 是 TLS 握手与连接状态摘要。
type TraceWroteHeaderFieldInfo ¶ added in v0.5.0
type TraceWroteRequestInfo ¶ added in v0.5.0
type TraceWroteRequestInfo struct {
Err error
}
type Transport ¶
type Transport struct {
// contains filtered or unexported fields
}
Transport 自定义 Transport(支持请求级配置)
type UploadProgressFunc ¶
UploadProgressFunc 文件上传进度回调函数
Source Files
¶
- client.go
- context.go
- defaults.go
- dialer.go
- errors.go
- options_body.go
- options_config.go
- options_header.go
- ping.go
- request.go
- request_body.go
- request_execution.go
- request_header.go
- request_multipart.go
- request_mutation.go
- request_network.go
- request_prepare.go
- request_query.go
- request_trace.go
- response.go
- retry.go
- tlsconfig.go
- tlssniffer.go
- tlsstats.go
- trace.go
- trace_summary.go
- transport.go
- types.go
- utils.go