surf

package module
v1.0.256 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: MIT Imports: 75 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README ΒΆ

Surf - Advanced HTTP Client for Go

Go Reference Coverage Status Go Mentioned in Awesome Go Ask DeepWiki

Surf is a powerful, feature-rich HTTP client library for Go that makes working with HTTP requests intuitive and enjoyable. With advanced features like browser impersonation, JA3/JA4 fingerprinting, and comprehensive middleware support, Surf provides everything you need for modern web interactions.

✨ Key Features

🎭 Browser Impersonation

  • Chrome & Firefox Support: Accurately mimic Chrome v158 (desktop/Android), Chrome v158 (iOS), and Firefox v160 (desktop) browser fingerprints
  • Platform Diversity: Impersonate Windows, macOS, Linux, Android, and iOS devices
  • TLS Fingerprinting: Full JA3/JA4 fingerprint customization for enhanced privacy
  • Automatic Headers: Proper header ordering and browser-specific values
  • WebKit Form Boundaries: Accurate multipart form boundary generation matching real browsers

πŸ”’ Advanced TLS & Security

  • Custom JA3/JA4: Configure precise TLS fingerprints with HelloID and HelloSpec
  • HTTP/3 Support: HTTP/3 over QUIC with customizable HTTP/3 settings
  • HTTP/2 & HTTP/3: Full HTTP/2 support with customizable settings (SETTINGS frame, window size, priority)
  • Ordered Headers: Browser-accurate header ordering for perfect fingerprint evasion
  • Certificate Pinning: Custom TLS certificate validation
  • DNS-over-TLS: Enhanced privacy with DoT support
  • Proxy Support: HTTP, HTTPS, SOCKS4 and SOCKS5 proxy configurations with UDP support for HTTP/3

πŸš€ Performance & Reliability

  • Connection Pooling: Efficient connection reuse with singleton pattern
  • Automatic Retries: Configurable retry logic with custom status codes
  • Response Caching: Built-in body caching for repeated access
  • Streaming Support: Efficient handling of large responses and SSE
  • Compression: Automatic decompression of gzip, deflate, brotli, and zstd responses
  • Keep-Alive: Persistent connections with configurable parameters

πŸ› οΈ Developer Experience

  • Standard Library Compatible: Convert to net/http.Client for third-party library integration
  • Fluent API: Chainable methods for elegant code
  • Middleware System: Extensible request/response/client middleware with priority support
  • Type Safety: Strong typing with generics support via enetx/g
  • Debug Mode: Comprehensive request/response debugging
  • Error Handling: Result type pattern for better error management
  • Context Support: Full context.Context integration for cancellation and timeouts

πŸ“¦ Installation

go get -u github.com/enetx/surf

Required Go version: 1.27+

πŸ”„ Standard Library Compatibility

Surf provides seamless integration with Go's standard net/http package, allowing you to use Surf's advanced features with any library that expects a standard *http.Client.

// Create a Surf client with advanced features
surfClient := surf.NewClient().
    Builder().
    Impersonate().Chrome().
    Session().
    Build().
    Unwrap()

// Convert to standard net/http.Client
stdClient := surfClient.Std()

// Use with any third-party library
// Example: AWS SDK, Google APIs, OpenAI client, etc.
resp, err := stdClient.Get("https://api.example.com")

Preserved Features When Using Std():

  • βœ… JA3/TLS fingerprinting
  • βœ… HTTP/2, HTTP/3 settings && fingerprinting
  • βœ… Browser impersonation headers
  • βœ… Ordered headers
  • βœ… Cookies and sessions
  • βœ… Proxy configuration
  • βœ… Custom headers and User-Agent
  • βœ… Timeout settings
  • βœ… Redirect policies
  • βœ… Request/Response middleware

Limitations with Std():

  • ❌ Retry logic (implement at application level)
  • ❌ Response body caching
  • ❌ Remote address tracking
  • ❌ Request timing information

πŸš€ Quick Start

Basic GET Request

Requires Go 1.27 or newer. Surf uses the released github.com/enetx/http module for HTTP/1 and HTTP/2, and github.com/enetx/quic-go for HTTP/3 and QUIC.

package main

import (
    "fmt"
    "log"
    "github.com/enetx/surf"
)

func main() {
    resp := surf.NewClient().Get("https://api.github.com/users/github").Do()
    if resp.IsErr() {
        log.Fatal(resp.Err())
    }

    fmt.Println(resp.Ok().Body.String().Unwrap())
}

JSON Response Handling

type User struct {
    Name     string `json:"name"`
    Company  string `json:"company"`
    Location string `json:"location"`
}

resp := surf.NewClient().Get("https://api.github.com/users/github").Do()
if resp.IsOk() {
    var user User
    resp.Ok().Body.JSON(&user)
    fmt.Printf("User: %+v\n", user)
}

🎭 Browser Impersonation

Chrome Impersonation

client := surf.NewClient().
    Builder().
    Impersonate().
    Chrome().        // Chrome v158
    Build().
    Unwrap()

resp := client.Get("https://example.com").Do()

Impersonate().Chrome() selects Chrome 158 for desktop and Android. JA().Chrome() and JA().Chrome158() select its TLS template. The public Chrome version-specific API exposes 158 only. The Chrome 158 audit records the release source comparison and ordinary Chromium captures, including server_padding, ORIGNOIP and Chrome-branded Client Hints. Chromium is the protocol reference; the selected OS supplies Chrome's User-Agent. The report identifies source-derived platform fixtures and retained independent historical HPACK references.

Impersonate().IOS().Chrome() selects Chrome 158 iOS branding over the separate captured WebKit TLS/HTTP2 shape. Its OS identity remains the verified iPhone identity; the new app-level UA is source-derived until a fresh device capture. It sends no Chromium Client Hints. Each platform keeps one current profile and its own golden reference.

Chrome desktop/Android automatically negotiate HTTP Client Hints on document navigations: Accept-CH is remembered per origin, and Critical-CH can restart a request once per origin in that navigation. Subsequent requests include available opted-in values. Firefox and iOS retain their own behavior.

client := surf.NewClient().Builder().Impersonate().Chrome().
    ClientHints().
    Architecture("x86").
    Bitness("64").
    PlatformVersion("19.0.0").
    Set().Build().Unwrap()

The nested builder also exposes FullVersion, FullVersionList, Model, WoW64, FormFactors, serialized Value, origin-cache Capacity, Lifetime, Clock, and the switches Enabled, ALPS, ClearSiteData. Defaults describe the selected profile, independent of the Go host OS. Automatic negotiation fills only absent hint fields; unavailable viewport/device metrics are not invented. ClearClientHints() resets learned opt-ins and ClientHintNames(url) returns a copy. See the runnable Client Hints example and independent Chromium reference. Authenticated HTTP/2 and HTTP/3 ALPS can add missing hints to a navigation on that connection, without remembering an origin opt-in. Relevant Clear-Site-Data directives clear remembered hints and suppress same-response negotiation. ALPS(false) and ClearSiteData(false) override those defaults. See the ALPS scope and browser evidence. DOM meta directives, frame permissions and disk persistence remain outside the HTTP client's navigation model.

Session() preserves cookies and enables TLS resumption where the profile supports it. Chrome desktop and Android add PSK on a new TLS 1.3 connection with a cached ticket; reusing an existing connection does not create another ClientHello. The verified iOS profile keeps full handshakes even with Session(); its cookies still persist.

HTTP/3 uses the minimal enetx QUIC fork with separate browser ClientHello templates. Independent browser fixtures cover supported QUIC/TLS parameters, SETTINGS and header order. The wire notes describe differences, including transport scheduling, pacing, recovery and platform coverage.

Firefox desktop uses the current 160 TLS template and headers. JA().Firefox() and JA().Firefox160() select that TLS fingerprint; JA().Firefox148() retains the native uTLS preset. Android and iOS keep their existing 148 placeholders until verified mobile captures are available.

Request header presets

Each browser has one authoritative header declaration: Chrome and Firefox. These files contain identity values, navigation/fetch defaults, ordered fields, pseudo-header order and protocol settings. Platform compatibility.go files preserve the public package entry points and delegate to these declarations.

Preset factories return a fresh g.MapOrd for a public profiles.HeaderContext. An explicit Sec-Fetch-Mode selects navigation or fetch; otherwise HeaderContext.Kind can select the scenario, followed by method defaults: GET/HEAD are navigation and other methods are fetch. Fluent request selectors work without requiring emitted Fetch Metadata:

client.Get(url).Fetch().Do()
client.Post(url).Navigation().Body("name=surf").Do()

Use Fetch() for a GET/HEAD to an API: those methods otherwise receive document navigation defaults. Use Navigation() for a POST representing form navigation: POST otherwise receives ordinary fetch defaults. The selection changes browser header defaults such as Accept, Fetch Metadata, Priority and cache directives. Get/Post and Body/Multipart still define the method and payload. Explicit headers and ordered maps retain precedence. GET/HEAD document requests and ordinary POST API requests already have the appropriate default and need no selector.

The context also carries the target OS, body/framing metadata, redirects, Critical-CH restart state and the actual HTTP protocol. Protocol 0 prepares logical defaults; 1, 2 or 3 selects the final layout on a private transport attempt, including fallback. Factories do not read the body. Buffered and streamed bodies use the same scenario declarations, with framing and replay determined by their actual body metadata.

Public SetHeaders and AddHeaders retain their existing g.MapOrd API. An explicitly supplied ordered map owns its listed field order, including after Client Hints negotiation or a redirect. Explicit values win over profile defaults; regular order, pseudo-header order and HTTP/1 casing metadata remain independent. The request path does not re-sort application-ordered maps through a preset. Explicit empty/nil entries in the underlying http.Header can suppress a default; empty MapOrd values reserve positions. Public profile .Headers functions remain factory adapters using an HTTP/2 layout and a plain HTTP method; use BuildRequestHeaders with HeaderContext for explicit protocol/body context.

See the runnable preset scenarios example for navigation, fetch, form POST and an explicit ordered map.

Document facts such as Origin, Referer and user activation belong to the application. For example, Firefox's ordinary fetch has Priority: u=4, while a native UI-triggered fetch can use a different priority. The transport does not infer a DOM interaction from the HTTP method.

Desktop HTTP origin policy also applies: on ordinary insecure HTTP, generated Client Hints and Fetch Metadata are omitted and Chrome/Firefox advertise gzip, deflate. HTTPS and trustworthy loopback origins retain their normal metadata and advanced encodings. Explicit application fields still win. A request's navigation/fetch scenario survives redirects independently of whether those metadata fields can be sent.

The header references retain actual HTTP/1 fields from ordinary Chromium 158 and Firefox 160. HTTP/2 and HTTP/3 tests apply documented protocol deltas to those references; they are local wire regressions, not native multiplexed-browser captures. Desktop observations do not establish Android or iOS parity: Firefox mobile retains its labeled 148 placeholders, and Chrome iOS retains a separate WebKit shape awaiting a fresh native device capture. Client Hints negotiation keeps the scope described above.

Firefox with Random OS

client := surf.NewClient().
    Builder().
    Impersonate().
    RandomOS().      // Randomly selects Windows, macOS, Linux, Android, or iOS
    Firefox().       // Firefox profile for the selected OS
    Build().
    Unwrap()

Platform-Specific Impersonation

// iOS Chrome
client := surf.NewClient().
    Builder().
    Impersonate().
    IOS().
    Chrome().
    Build().
    Unwrap()

// Android Chrome
client := surf.NewClient().
    Builder().
    Impersonate().
    Android().
    Chrome().
    Build().
    Unwrap()

πŸš€ HTTP/3 & QUIC Fingerprinting

Chrome HTTP/3 with Automatic Detection

// Automatic HTTP/3 with Chrome fingerprinting
client := surf.NewClient().
    Builder().
    Impersonate().Chrome().
    ForceHTTP3().    // Auto-detects Chrome and applies appropriate HTTP/3 settings
    Build().
    Unwrap()

resp := client.Get("https://cloudflare-quic.com/").Do()
if resp.IsOk() {
    fmt.Printf("Protocol: %s\n", resp.Ok().Proto) // HTTP/3.0
}

Firefox HTTP/3

// Firefox with HTTP/3 fingerprinting
client := surf.NewClient().
    Builder().
    Impersonate().Firefox().
    ForceHTTP3().    // Auto-detects Firefox and applies Firefox HTTP/3 settings
    Build().
    Unwrap()

resp := client.Get("https://cloudflare-quic.com/").Do()

Manual HTTP/3 Configuration

// Custom fingerprint settings
client := surf.NewClient().
    Builder().
    HTTP3Settings().Grease().Set().
    Build().
    Unwrap()

Chrome 158 transport defaults follow the selected protocol, including fallback: HTTP/1.1 sends Connection and lowercase Client Hints without a default Priority. HTTP/2 and HTTP/3 preserve their own ordered defaults. Custom values take precedence. HTTP3Settings().CoalesceRequestHeaders(true) stages initial priority, HEADERS and bodyless FIN together when stream credit permits. QPACK distinguishes an omitted peer capacity from an explicit zero through QpackEncoderCapacityRequiresSetting and QpackEncoderZeroCapacity.

ForceHTTP3() attempts QUIC directly and registers the transport itself. UDP unavailability and TCP-only proxies retain HTTP/2/HTTP/1 fallback; a SOCKS5 proxy with UDP support can carry HTTP/3. Proxy routes keep separate TCP pools while retaining the selected TLS profile. Chrome 158 audit.

Request encoding and control frames

HTTP/2 header encoding and HTTP/3 control frames can be configured through the same fluent builders as SETTINGS. Browser policy stays in Surf; the HTTP and QUIC modules expose generic mechanisms. HPACK, Huffman coding and QPACK's static table retain their official implementations; dynamic QPACK state is isolated in the existing QUIC fork.

client := surf.NewClient().Builder().Impersonate().Firefox().
    HTTP2Settings().
    HpackRepresentation("x-private", surf.HPACKNeverIndex).
    Set().
    HTTP3Settings().
    QpackNeverIndex("x-private").
    Set().Build().Unwrap()
defer client.Close()

HpackPolicy, HpackIndexingLimit, HpackHuffman and HpackNameReferencePolicy control literal representations and new table entries. HPACKNameReferenceFirst selects the first matching static name, as Chromium does. HPACKIncrementalIndexing reuses exact entries and emits incremental literals even when an entry is too large, emptying the table in that case. These are selected by the Chrome desktop and Android profiles; native defaults remain available through the same builder. MaxEncoderHeaderTableSize independently bounds the request encoder's table; HeaderTableSize advertises the response decoder's capacity. The browser profiles accept peer encoder-table growth up to the native engine's math.MaxInt32 limit. HpackDeduplicateTableSizeUpdates controls redundant capacity notifications. HeaderPriority selects HTTP/2 priority per request; ChainStreamDependencies links it to eligible open streams. Trailers inherit the header encoding policy, without receiving the request's HEADERS priority.

ControlGreaseFrames / RequestGreaseFrames accept reserved frames; their Factory variants generate fresh values per connection or request. PriorityUpdates controls initial HTTP/3 priority frames independently of GREASE and local QUIC StreamPriority. QpackSplitCookies and QpackNeverIndex control request fields. Browser presets select these independently:

Behavior Chrome 158 desktop / Android Firefox 160 desktop
HPACK varying :path Literal without indexing Literal without indexing, including static paths
HPACK Authorization Normal indexing Never indexed
HPACK Cookie Split pairs, normal indexing Split pairs; pairs shorter than 20 bytes never indexed
HPACK new entries Incremental literals; an oversized entry empties the table At most half the table; none when capacity is below 128
HPACK literal name reference First static match, then newest dynamic name Exact match, otherwise last matching name
HPACK Huffman When shorter Always for literal strings
Repeated unchanged HPACK capacity No new instruction Table-size instruction queued
HTTP/3 Cookie Separate field per pair Preserve a single joined field
QPACK insertion Eligible names and values Only names absent from both tables
QPACK Huffman Only when strictly shorter Always for literal strings
QPACK Insert names Static/dynamic name references when available Literal names
QPACK Base Required Insert Count Insert count before the section; post-base references
QPACK draining Oldest quarter; duplicate eligible draining entries No draining reservation
QPACK insertion failure Continue trying later fields Stop new insertions for this section
Control GREASE type 31*n+33, 32-bit draw 31*n+33, 57-bit draw
Control GREASE payload Length n%4 Independent draw, length 0–7
Initial HTTP/3 priority update Explicit nondefault Priority Disabled; Neqo uses updates for changed priority

Sources are pinned to Chrome 158's QUICHE revision and Firefox 160.0. The profile functions link directly to the corresponding browser source files. iOS profiles keep their WebKit behavior; these desktop engine policies are not applied to iOS. Browser resource-loading decisions remain outside this API. The QPACK audit records exact field-section and encoder-stream comparisons. These do not establish complete packet timing, loss recovery or browser workload equivalence.

See the HTTP/2 custom example and HTTP/3 custom example for overrides.

QUIC ACK scheduling

QUIC receive ACK scheduling is configurable through QUICSettings(): AckPacketThreshold, AckDecimation(after, threshold), AckDelayRTTDivisor, MinAckDelay, AckReordering, AckMissingPacketLimit and AckECN. Chrome profiles select the 2-to-10 threshold transition by packet-number span; Firefox retains two packets and a 20 ms deadline. ResetAckPolicy restores native receive scheduling. These controls do not negotiate ACK_FREQUENCY. See browser source audit and actual ACK observations and the custom HTTP/3 example.

HTTP/3 Compatibility & Fallbacks

HTTP/3 automatically handles compatibility issues:

// With HTTP proxy - automatically falls back to HTTP/2
client := surf.NewClient().
    Builder().
    Proxy("http://proxy:8080").    // HTTP proxies incompatible with HTTP/3
    ForceHTTP3().                  // Will use HTTP/2 instead
    Build().
    Unwrap()

// With SOCKS5 proxy - HTTP/3 works over UDP
client := surf.NewClient().
    Builder().
    Proxy("socks5://127.0.0.1:1080").    // SOCKS5 UDP proxy supports HTTP/3
    ForceHTTP3().                        // Will use HTTP/3 over SOCKS5
    Build().
    Unwrap()

// With DNS settings - works seamlessly
client := surf.NewClient().
    Builder().
    DNS("8.8.8.8:53").   // Custom DNS works with HTTP/3
    ForceHTTP3().
    Build().
    Unwrap()

// With DNS-over-TLS - works seamlessly
client := surf.NewClient().
    Builder().
    DNSOverTLS().Google().   // DoT works with HTTP/3
    ForceHTTP3()
    Build().
    Unwrap()

Key HTTP/3 Features:

  • βœ… QUIC Controls: Browser profiles and externally configurable transport parameters
  • βœ… Header Ordering: Explicit regular and pseudo-header order
  • βœ… SOCKS5 UDP Support: HTTP/3 works seamlessly over SOCKS5 UDP proxies
  • βœ… Automatic Fallback: HTTP/2 or HTTP/1.1 fallback retains the configured TCP TLS fingerprint and protocol-specific header defaults
  • βœ… DNS Integration: Custom DNS and DNS-over-TLS support
  • βœ… TLS Templates: Separate HTTP/3 ClientHello templates with Surf's minimal uTLS fork
  • βœ… Order Independence: ForceHTTP3() works regardless of call order

Native HTTP/3 configuration

QUICSettings() uses the same chain-and-Set() pattern as HTTP2Settings() and HTTP3Settings(). Each method changes one option while preserving Surf's other defaults or the selected browser profile. Reopening either settings chain retains earlier values. ForceHTTP3() selects the QUIC transport.

client := surf.NewClient().Builder().
    Impersonate().Chrome().
    ForceHTTP3().
    QUICSettings().
    InitialStreamReceiveWindow(6 << 20).
    InitialConnectionReceiveWindow(15 << 20).
    InitialPacketSize(1250).
    DisablePathMTUDiscovery(true).
    ConnectionIDLength(8).
    EnableDatagrams(true).
    Set().
    HTTP3Settings().
    StreamPriority(0, true).
    MaxResponseHeaderBytes(262144).
    Set().
    Build().Unwrap()

QUIC methods cover versions, handshake/idle timeouts, keep-alive, flow-control windows, stream limits, packet size/PMTU, token stores, reliable resets and tracing. Versions accepts constants such as quic.Version1 from github.com/enetx/quic-go. Zero values retain quic-go's field-specific meaning; KeepAlivePeriod(0) disables keep-alive. InitialStreamReceiveWindow replaces per-direction window overrides. Explicit ConnectionIDLength(0) uses empty source IDs and dedicated sockets; leaving it unset retains the profile's value or the native four-byte default.

HTTP3Settings() configures ordered SETTINGS, QPACK, header limits and local stream priority. AdditionalSettings merges settings, preserving existing positions. QUICSettings().EnableDatagrams configures both transport and HTTP/3 support.

QUICSettings().LegacyAckFrequency(time.Millisecond).Set() opts into the legacy ACK_FREQUENCY receiver and advertises its minimum delay. Firefox configures this through the same builder; Chrome leaves it off. Zero disables the extension. Peer requests can change local ACK tolerance, delay and ignore_order behavior; local ACK settings apply until the first valid request. This is separate from MinAckDelay, which is the local RTT-based timer floor.

QUICSettings().PeerAckFrequencyPolicy(policy).Set() independently configures outgoing legacy requests, enabled only after the peer advertises its minimum and the handshake completes. Firefox uses live congestion window, datagram size and RTT to target four ACKs per RTT, with tolerance 2..256 and 25% delay hysteresis. Chrome leaves the sender disabled. Pass nil to disable outgoing requests. Callbacks must be concurrency safe, return promptly and provide valid targets even when no update is requested; the engine manages sequencing, ACK/loss and PTO. InitialCongestionWindowPackets(n) selects a starting window in accounting segments (2..10000); zero keeps the native count. Firefox selects 10 path-MTU segments with RFC 9438 CUBIC and classic byte-based slow start. Chromium selects 32 segments of 1460 bytes, byte-mode CUBIC, two emulated connections and original HyStart. These are source defaults; browser experiments can override them. CongestionControl, SlowStart, CongestionControlSegmentSize and CongestionControlConnections expose the same fluent controls to users. Pacing and recovery scheduling retain the engine's behavior. The custom HTTP/3 example demonstrates both controls through the builder.

HTTP/3 can race connection preparation against a TCP backup:

client := surf.NewClient().Builder().Impersonate().Firefox().ForceHTTP3().
    HTTP3Settings().ConnectionRacing(true).Set().Build().Unwrap()
defer client.Close()

Automatic discovery races eligible H3 alternatives; in forced-H3 mode, ConnectionRacing(true) enables the backup explicitly. Profiles select the delay policy. Firefox uses the pending-transaction backup timer of 100ms. Chrome's policy uses this client's observed QUIC success across origins, with failure and RTT kept per origin. The desktop reference's Chromium trial adds 50ms; Android adds its default 100ms. Both cap the total at three seconds. With no RTT for a new origin, these give 350ms and 400ms after QUIC has worked elsewhere in the client. Closing idle connections retains this history; a new built client starts fresh. The source and native capture audit records the scope: OS network-change notifications, persisted network state and the browser's full DNS/Alt-Svc/Happy Eyeballs job scheduler are not reproduced. Chrome starts its backup timer after QUIC DNS and socket preparation. A reusable H2 session suppresses the delay, including when its streams are occupied. An already confirmed H3 session retains priority. TCPFallbackAfterQUICStart(bool) exposes the timer start point through the same builder. TCPFallbackDelay(d) overrides the policy and restores request-start timing (zero starts both preparations immediately). Call TCPFallbackAfterQUICStart(true) after it to retain an explicit delay measured from QUIC initialization. ConnectionRacingPolicy(func(ConnectionRacingInfo) time.Duration) supplies a custom nonnegative delay; callbacks must return promptly and be concurrency safe. QUICWorked still describes only the current origin; the additional QUICWorkedInClient observation describes the shared HTTP/3 transport session. Explicit delays and custom policies retain their own behavior.

Requests requiring 1-RTT wait for connection selection before sending. The selected transport owns their body, including non-replayable StreamingBody readers. With EarlyData(true), eligible bodyless GET/HEAD can use cached early keys during preparation. Chrome additionally requires confirmed QUIC support in this built client's transport before admitting an early application request. A shared ticket alone does not establish that support. TLS early-data offers and H3 setup remain possible while the request waits for verified TLS. EarlyRequestPolicy(func(ConnectionRacingInfo) bool) customizes that extra gate; nil removes it without bypassing the GET/HEAD/body or EarlyData checks. Chrome selects admitted early-ready QUIC; Firefox retains its TCP backup until the QUIC handshake finishes. A ready backup can cancel that early GET/HEAD attempt and send it over TCP. EarlyDataBackup(bool) exposes the same policy through the public builder. Confirmed exchanges do not race application requests; ordinary explicit-rejection/reuse retries still apply. Compatible waiters share preparation; canceling one waiter preserves others. A QUIC handshake that loses to TCP can finish into the shared pool for later use. Close cancels preparation; CloseIdleConnections also stops selected background attempts. TCP dials and idle connections retain native transport cleanup rules.

Connection racing requires keep-alives. Early data remains an explicit opt-in and requires a session cache; unsafe requests retain full-handshake selection. HTTP CONNECT proxies use the ordinary TCP path; SOCKS5 can prepare both protocols. Disabling connection racing retains sequential fallback. Browser policy history is local to the client, with inactive history bounded to 256 origins.

See the early-data racing example and source/capture report.

HTTP3Settings().Grease().Set() generates a fresh reserved SETTINGS pair for each new connection. Chrome profiles use two independent uint32 draws, matching the browser's identifier/value ranges. GreaseFactory(factory) accepts a custom func() (id uint64, value uint64, err error); GreaseFactory(nil) disables it. The callback must be concurrency safe and return promptly. Invalid identifiers, duplicate configured identifiers and errors fail before initial control writes. Repeated requests on one connection keep the SETTINGS already sent.

Stream priority controls the local QUIC sender. It does not add a Priority header or send HTTP/3 PRIORITY_UPDATE frames. Per-request overrides are available through http3.WithStreamPriority(ctx, http3.StreamPriority{...}). The wire test notes describe verified parameters and remaining gaps in browser HTTP/3 matching.

Handshake controls also use QUICSettings(): StreamReceiveWindows(local, remote, uni), MaxUDPPayloadSize, MaxDatagramFrameSize, MaxAckDelay, ActiveConnectionIDLimit, InitialDestinationConnectionIDLength, InitialPacketNumber and DisableClientHelloScrambling. OmitMaxUDPPayloadSize(true) provisions the protocol default receive size. A later MaxUDPPayloadSize(size) resumes advertising an explicit limit. InitialPacketNumber(number) replaces a profile's packet-number factory with that fixed value.

Initial packet layout and handshake flights are independently configurable:

builder.QUICSettings().
    InitialPaddingMode(surf.InitialPaddingDatagram).
    HandshakeAckBeforeData(true).
    SortConnectionIDFrames(true).
    Set()

The Firefox profile selects these controls. Datagram padding is a zero tail after long-header packets; a final 1-RTT packet carries encrypted padding instead. Separating ACK and Finished adds no artificial timer and preserves TLS verification. InitialPaddingPacket and HandshakeAckBeforeData(false) restore native framing.

TransportParameterOrder(ids...), TransportParameter(id, encodedValue) and DisableTransportParameterGrease(bool) configure parameter encoding without a layout struct. Input slices are copied. These setters amend each fresh layout produced by a browser factory, preserving its other values and randomization. Disabling GREASE also removes reserved parameters generated by the browser factory; enabling it selects the native QUIC generator. TransportParametersFactory and InitialPacketNumberFactory allow custom per-attempt generation. Factories may run concurrently. The low-level HTTP3Settings().QUICConfig and ClientHandshake entry points remain available for existing callers; no configuration structs are required by the fluent API.

ClientHelloSpec(*utls.ClientHelloSpec) supplies a private template snapshot; ClientHelloFactory(func() (utls.ClientHelloSpec, error)) produces a fresh template per attempt. These accept explicit QUIC templates with ALPN and transport-parameter extensions. TCP JA() templates are independent and are not silently reused. Certificate verification and the supplied TLS session cache are retained. Invalid templates return errors. Wire notes document the remaining adapter limits and the migration status.

Surf uses the published github.com/enetx/http and github.com/enetx/quic-go modules without local replacements. HTTP/3 is imported from github.com/enetx/quic-go/http3; no uTLS dependency fork is required. Sibling checkouts can be combined in a parent Go workspace during development: go work init ./http ./quic-go ./surf. This keeps local paths out of release module files.

Nonzero QpackMaxTableCapacity enables a bounded receive-side dynamic QPACK table; QpackBlockedStreams limits waiting request streams. Feedback, cancellation and header-size limits are enforced. QpackDynamicTable(true) separately enables dynamic request headers and trailers, capped by peer SETTINGS and the local QpackEncoderTableCapacity budget. Chrome and Firefox desktop profiles enable it.

QPACK stream behavior uses the same HTTP/3 settings chain:

builder.HTTP3Settings().
    QpackDynamicTable(true).
    QpackHuffman(surf.QPACKHuffmanAuto).
    QpackIndexing(surf.QPACKIndexAll).
    QpackDrainingFraction(.25).
    QpackPostBaseReferences(false).
    QpackLiteralInsertNames(false).
    QpackStopOnInsertionFailure(false).
    QpackMaxTrackedSections(4096).
    QpackStreamOrder(surf.QPACKDecoderStream, surf.QPACKEncoderStream).
    QpackEagerStreamTypes(false).
    QpackEncoderTableCapacity(65536).
    QpackEncoderCapacityTiming(surf.QPACKCapacityBeforeHeaders).
    Set()

QpackStreamOrder reserves IDs after the control stream while credit permits; QpackEagerStreamTypes chooses startup type bytes or type bytes with the first instruction. Capacity announcements use the smaller of the peer's limit and QpackEncoderTableCapacity. They can be queued after peer SETTINGS or when encoding the next outgoing HEADERS block. QpackEncoderZeroCapacity(true) also emits the zero-capacity instruction, initializing a lazy encoder stream. Without peer SETTINGS, requests remain static and do not wait. Independent QUIC streams retain their native delivery ordering.

QpackIndexingPolicy optionally filters new insertions. QpackNeverIndex prevents insertion and emits literals with N=1. Unacknowledged entries and entries used by outstanding sections cannot be evicted. Section ACKs are processed in FIFO order on each stream; cancellation releases that stream's sections without advancing the acknowledged insert count. At the tracking budget or when the bounded encoder queue is full, new sections use static encoding without waiting. The default tracking budget is 4096 sections; zero restores that default.

Chrome desktop/Android reserve decoder then encoder streams, use lazy type bytes and defer capacity announcements to HEADERS. Firefox desktop reserves encoder then decoder streams, writes types eagerly and queues capacity after SETTINGS. Each profile's behavior can be overridden through HTTP3Settings(); the QUIC fork exposes only generic controls. See the wire notes for source references and the limits of the browser comparison.

HTTP/3 request bodies have separate controls for reads and DATA framing:

builder.HTTP3Settings().
    RequestBodyBufferSize(32 << 10).
    MaxDataFrameSize(16 << 10).
    Set()

RequestBodyBufferSizePolicy(func(contentLength int64) int) optionally selects reads per request; unknown lengths are -1, and zero uses the native 8 KiB buffer. RequestBodyBufferSize clears a previous policy. Both size options accept 0 through 16 MiB; MaxDataFrameSize(0) keeps one DATA frame per write. These options do not set QUIC packet boundaries. Chrome desktop/Android select a buffer between 14,520 and 371,712 bytes using the body length. Firefox desktop uses the shipped 32,768-byte network segment preference. Firefox's first large DATA boundary can still differ because Necko includes serialized request headers in that segment.

Use request.HTTP3PriorityUpdates(func(*surf.HTTP3PriorityUpdater)) to retain a handle for an open request. Its Update(urgency, incremental) method sends an RFC 9218 control frame, suppresses repeats, validates urgency 0–7, and rejects completed/canceled requests. (3, false) restores the default. The callback runs after request HEADERS and must return promptly; each retry gets a fresh handle. This does not change StreamPriority, which schedules local uploads. CompactPriorityUpdates(true) selects Firefox's comma formatting; Chrome uses comma-space. No resource loading policy is added.

HTTP3Settings().EarlyData(true).Set() opts bodyless GET/HEAD into 0-RTT with standard TLS or browser ClientHello templates (including ECH) and a configured tls.ClientSessionCache. Enable it only for requests whose replay is acceptable. POST and requests with bodies wait for the handshake. Rejection and HTTP 425 permit one 1-RTT retry. It is disabled by default. It supports connection racing and address preparation; the profile controls when an early-ready connection wins and whether TCP preparation continues. See the early-data racing report.

client := surf.NewClient().Builder().ForceHTTP3().
    TLSConfig(&tls.Config{ClientSessionCache: tls.NewLRUClientSessionCache(32)}).
    HTTP3Settings().EarlyData(true).Set().Build().Unwrap()
defer client.Close()

The HTTP/3 behavior report records browser captures, source references and remaining differences.

Chrome desktop/Android and Firefox desktop supply separate QUIC TLS factories; iOS and Firefox mobile retain their previous defaults pending browser captures. Firefox advertises compatible v1/v2 switching (RFC 9368/9369) and legacy ACK_FREQUENCY. Its profile starts with v1 and lists v2 before v1 in authenticated version information. QUICSettings().CompatibleVersionNegotiation(true) enables the same client mechanism for custom configurations; Versions selects allowed versions and the first flight. Native clients keep it disabled. Version validation, Retry, key changes and version-scoped session/token caches are handled by the engine. QUICSettings().ResumeVersion(true).Set() starts a new connection with the version stored in an available, unexpired TLS ticket for that origin. Firefox enables it; Chrome retains its configured version. Without a usable ticket, the configured first version applies. This uses the client's existing TLS cache, respects allowed versions and keeps no separate disk history. See the session-version source and capture report. All browser values and randomization policy live in Surf; the QUIC fork has no built-in browser presets or uTLS dependency.

Browser QUIC profiles use the same layout in profiles/chrome/quic/ and profiles/firefox/quic/: config.go implements ConfigureQUIC as a chain of the same setters exposed by QUICSettings(), including handshake, TLS and CID options. Profiles do not construct native QUIC configuration structs or share mutable configuration objects. Each application starts with fresh builder state. KeepAlivePeriod(0) is explicit to retain the browser profiles' disabled keep-alive. client_hello.go builds a fresh TLS template, transport_parameters.go owns per-attempt parameter layout and randomization, and qpack.go selects stream initialization and capacity timing. Platform variants select these profiles; HTTP/3 SETTINGS remain in their platform's http3.go.

The profile chains serve as manual configuration examples. Their public NewClientHelloSpec, NewTransportParameters and Firefox's NewInitialPacketNumber factories can be reused in application builder chains. profiles.Variant.ConfigureQUIC uses the fluent profiles.QUICConfig contract; Surf's adapter forwards it to the public setters and the dispatcher calls Set().

The browser example selects its OS and browser explicitly in code. To compare with the supplied macOS Firefox capture, select profile.MacOS(). Firefox desktop automatically adds alt-used on HTTP/3 attempts using the current destination authority:

go run ./examples/http/http3

The custom HTTP/3 example demonstrates builder overrides for QUIC windows, handshake parameters, TLS factory, CID length, QPACK, datagrams, local header limits and stream priority. -profile chrome or -profile firefox starts from fresh browser defaults; -profile custom sets individual transport options through QUICSettings(). Custom values change the resulting fingerprint.

Chrome desktop/Android and Firefox desktop also enable automatic HTTP/3 discovery. Use SecureTLS() so Alt-Svc advertisements can be authenticated. A new origin uses TCP until a valid Alt-Svc or usable HTTPS DNS binding is available; connection preparation then races without reading or replaying the request body. ForceHTTP1() / ForceHTTP2() take precedence, while ForceHTTP3() retains its direct QUIC attempt. HTTP3Settings().Discovery(false).Set() disables discovery. The discovery example demonstrates this flow with an ordinary verified client.

Alternatives and failure history are bounded per client and origin. Alt-Svc expiry, Age, clear, alternative host/port, original SNI and certificate verification are retained. HTTPS DNS uses the configured DNS/DoT dial hook and system resolver addresses on systems exposing resolv.conf; it never substitutes a public resolver. HTTPSRecordsLookup integrates platform or application DNS resolvers elsewhere. Bindings support priority, alias chains, ALPN, port, IP hints, mandatory keys and ECH. DNS bindings also route TCP-only services without changing Host/SNI; no-default-alpn can exclude the TCP backup. ECH configuration is retained on both QUIC and TCP preparation, using standard TLS configuration and Surf's uTLS adapter. Rejected ECH is not retried without ECH. Proxies bypass local HTTPS discovery. Application-owned transports/TLS dialers and disabled TCP keep-alives retain their existing connection policy.

Chrome 158 and Firefox 160 provide real-ECH inner ClientHello policies from their browser profile packages. The minimal enetx/utls fork preserves their cipher order and complete shared extension payloads, including fields unknown to Go. Custom templates can supply a policy through JA().ECHClientHelloInner or QUICSettings().ECHClientHelloInner before the terminal builder method. Real ECH supports TLS 1.3 session resumption on TCP and QUIC. The engine binds the full private ClientHello and keeps real session identities out of the public hello. Chrome omits the outer PSK; Firefox randomizes its identity, age and binder. Opt-in HTTP3Settings().EarlyData(true).Set() also works with browser templates and ECH, for bodyless GET/HEAD only. It requires a TLS session cache; POST and requests with bodies wait for the full handshake. The ECH verification report distinguishes native Chrome and independently decrypted Firefox TCP/QUIC captures, source checks and local integration tests. The ECH example prints the negotiated protocol and ConnectionState.ECHAccepted; run it with go run ./examples/tls/ech. It uses www.cloudflare-quic.com, which advertises both h3 and ECH at the time of verification. www.cloudflare.com currently advertises h3 without ECH. Forced HTTP/1, HTTP/2 and HTTP/3 retain enabled HTTPS DNS discovery for TLS metadata. Built-in A/AAAA and HTTPS queries start together; Surf's own dialers reuse those address results. Application-owned dialers retain resolution and routing control. Chrome's optional HTTPS timer starts after address queries finish (20% of their duration, bounded to 5–50 ms), matching its default opportunistic ECH mode. Firefox waits for the HTTPS result or resolver/request deadline. HTTPSRecordsWait(nil) removes the supplemental deadline, including when an application requires HTTPS metadata. With Chrome's default opportunistic policy, a late HTTPS answer can therefore leave ECH unused even on a capable endpoint. Waiting longer cannot supply ECH when DNS advertises no config. Explicit lookup callbacks own their timing. Address results remain scoped to the lookup flight, since Go's resolver does not expose their TTL. Authenticated ECH rejection can reconnect once with nonempty retry configs. Certificate failures, a second rejection or missing configs fail without a plaintext retry; DNS caches and the caller's TLS config remain unchanged. HTTPS queries use the same custom .DNS("address:53") or .DNSOverTLS() resolver as A/AAAA queries, regardless of its position relative to the profile selector. An explicitly supplied HTTPSRecordsLookup owns HTTPS queries instead.

QUIC profiles now include send scheduling as fluent configuration. Chromium uses scheduled pacing with PRR and a 2000 Γ— 1460-byte window ceiling. Firefox uses a two-packet leaky bucket, classic recovery and persistent-congestion detection, without the engine's fixed congestion-window ceiling. Firefox has separate Initial, Handshake and Application Data wire counters, with no artificial random or PTO gaps; Chromium keeps a shared counter. QUICSettings() exposes Pacing, PacingGains, PacingBurstPackets, PacingGranularity, PacingLumpyBurst, ProportionalRateReduction, RecoveryBurstPackets, PersistentCongestionThreshold, MaxCongestionWindowPackets and SeparatePacketNumberSpaces and PacketNumberSkipping. Optional AddressFallbackDelay enables staggered QUIC address attempts; this custom override is not enabled indiscriminately in browser profiles. Native packet-history and integer safety limits still apply.

Chrome also enables CachedInitialRTT(0x3127, 10*time.Millisecond, time.Second) and InitialPTOMultiplier(3). A cold connection omits the RTT hint; replacing the connection on the same client advertises its measured per-origin SRTT. Proxy paths are excluded. The wire value stays measured while the local initial estimate is clamped. InitialRTT supplies an explicit local-only estimate. See the two-connection example and pinned source checks.

These controls reproduce the verified mechanisms and preset source values. Browser DNS integration, persisted network experiments, OS scheduling and NIC packet timing remain outside an exact browser identity claim.

HTTP3Settings().AltUsed(false).Set() disables the Firefox desktop profile's automatic alt-used header; AltUsed(true) enables it for a custom profile. For direct HTTP/3 the value follows the request URL. Discovery uses the actual connected alternative authority; port 443 is omitted and other ports are preserved. An explicit Alt-Used header takes precedence. Automatic values are added to a private HTTP/3 attempt, so HTTP/1/2 fallback does not inherit them.

πŸ”§ Advanced Configuration

Custom JA3 Fingerprint

// Use specific browser versions
client := surf.NewClient().
    Builder().
    JA().
    Chrome().     // Latest Chrome
    Build().
    Unwrap()


// Randomized fingerprints for evasion
client := surf.NewClient().
    Builder().
    JA().
    Randomized().    // Random TLS fingerprint
    Build().
    Unwrap()

// With custom HelloID
client := surf.NewClient().
    Builder().
    JA().
    SetHelloID(utls.HelloChrome_Auto).
    Build().
    Unwrap()

// With custom HelloSpec
client := surf.NewClient().
    Builder().
    JA().
    SetHelloSpec(customSpec).
    Build().
    Unwrap()

HTTP/2 Configuration

client := surf.NewClient().
    Builder().
    HTTP2Settings().
    HeaderTableSize(65536).
    EnablePush(0).
    InitialWindowSize(6291456).
    MaxHeaderListSize(262144).
    ConnectionFlow(15663105).
    Set().
    Build().
    Unwrap()

HTTP/3 Configuration

client := surf.NewClient().
    Builder().
	HTTP3Settings().
	QpackMaxTableCapacity(65536).
	MaxFieldSectionSize(262144).
	QpackBlockedStreams(100).
	H3Datagram(1).
	Grease().
	Set().
    Build().
    Unwrap()

Proxy Configuration

// Single proxy
client := surf.NewClient().
    Builder().
    Proxy("http://proxy.example.com:8080").
    Build().
    Unwrap()

SOCKS5 UDP Proxy Support

Surf supports HTTP/3 over SOCKS5 UDP proxies, combining the benefits of modern QUIC protocol with proxy functionality:

// HTTP/3 over SOCKS5 UDP proxy
client := surf.NewClient().
    Builder().
    Proxy("socks5://127.0.0.1:1080").
    Impersonate().Chrome().
    ForceHTTP3().  // Uses HTTP/3 over SOCKS5 UDP
    Build().
    Unwrap()

// SOCKS5 with custom DNS resolution
client := surf.NewClient().
    Builder().
    DNS("8.8.8.8:53").              // Custom DNS resolver
    Proxy("socks5://proxy:1080").   // SOCKS5 UDP proxy
    ForceHTTP3().                   // HTTP/3 over SOCKS5
    Build().
    Unwrap()

πŸ”Œ Middleware System

Request Middleware

client := surf.NewClient().
    Builder().
    With(func(req *surf.Request) error {
        req.AddHeaders("X-Custom-Header", "value")
        fmt.Printf("Request to: %s\n", req.GetRequest().URL)
        return nil
    }).
    Build().
    Unwrap()

Response Middleware

client := surf.NewClient().
    Builder().
    With(func(resp *surf.Response) error {
        fmt.Printf("Response status: %d\n", resp.StatusCode)
        fmt.Printf("Response time: %v\n", resp.Time)
        return nil
    }).
    Build().
    Unwrap()

Client Middleware

client := surf.NewClient().
    Builder().
    With(func(client *surf.Client) error {
        // Modify client configuration
        client.GetClient().Timeout = 30 * time.Second
        return nil
    }).
    Build().
    Unwrap()

πŸ“€ Request Types

POST with JSON

user := map[string]string{
    "name": "John Doe",
    "email": "john@example.com",
}

resp := surf.NewClient().
    Post("https://api.example.com/users").
    Body(user).
    Do()

Form Data

// Standard form data (field order not guaranteed)
formData := map[string]string{
    "username": "john",
    "password": "secret",
}

resp := surf.NewClient().
    Post("https://example.com/login").
    Body(formData).
    Do()

// Ordered form data (preserves field insertion order)
orderedForm := g.NewMapOrd[string, string]()
orderedForm.Insert("username", "john")
orderedForm.Insert("password", "secret")
orderedForm.Insert("remember_me", "true")

resp := surf.NewClient().
    Post("https://example.com/login").
    Body(orderedForm).
    Do()

File Upload

// Single file upload
mp := surf.NewMultipart().
    File("file", g.NewFile("/path/to/file.pdf"))

resp := surf.NewClient().
    Post("https://api.example.com/upload").
    Multipart(mp).
    Do()

// With additional form fields
mp := surf.NewMultipart().
    Field("description", "Important document").
    Field("category", "reports").
    File("file", g.NewFile("/path/to/file.pdf"))

resp := surf.NewClient().
    Post("https://api.example.com/upload").
    Multipart(mp).
    Do()

Multipart Form

// Simple multipart form with fields only
mp := surf.NewMultipart().
    Field("field1", "value1").
    Field("field2", "value2")

resp := surf.NewClient().
    Post("https://api.example.com/form").
    Multipart(mp).
    Do()

// Advanced multipart with files from different sources
mp := surf.NewMultipart().
    Field("description", "Multiple files").
    File("document", g.NewFile("/path/to/doc.pdf")).               // Physical file
    FileBytes("data", "data.json", g.Bytes(`{"key": "value"}`)).   // Bytes with custom filename
    FileString("text", "note.txt", "Hello, World!").               // String content
    FileReader("stream", "upload.bin", someReader).                // io.Reader
    ContentType("application/pdf")                                 // Custom Content-Type for last file

resp := surf.NewClient().
    Post("https://api.example.com/upload").
    Multipart(mp).
    Do()

πŸ”„ Session Management

Persistent Sessions

client := surf.NewClient().
    Builder().
    Session().        // Enable cookie jar
    Build().
    Unwrap()

// Login
client.Post("https://example.com/login").Body(credentials).Do()

// Subsequent requests will include session cookies
resp := client.Get("https://example.com/dashboard").Do()

TLS Ticket Cache

Session() enables browser-owned TCP and QUIC ticket queues alongside cookies. Chrome 158 keeps two tickets per server and consumes TLS 1.3 tickets once; its legacy TCP TLS 1.2 tickets remain reusable. Firefox 160 keeps ten tokens in expiration order and consumes each selected token. Its TCP and QUIC keys share an 8 MiB storage budget, using Brotli quality 1 and eviction of individual tokens nearest expiration across keys. Chrome retains independent caches.

The byte charge includes each ticket's key and stored payload. Surf compresses Go's public serialized TLS state; NSS has a different opaque representation. Exact record sizes and the number of sessions fitting in 8 MiB therefore differ. The 1024-key guard also bounds Surf's consumed-ticket history. This budget does not measure the full Go heap or provide browser disk persistence.

Override the policy with Surf's nested builder. Browser defaults are applied first, then these explicit settings, regardless of where Impersonate() appears in the chain:

client := surf.NewClient().Builder().
    Impersonate().Chrome().
    Session().
    SessionCache().
        Capacity(256).
        TCP().TicketsPerKey(2).ReuseTLS12(true).
        QUIC().TicketsPerKey(2).ClearEarlyDataOnReject(true).
        Set().
    Build().Unwrap()

Settings target both protocols initially. TCP(), QUIC() and Both() select which caches subsequent calls configure. Reopening SessionCache() starts with both selected. Set() returns the client builder; validation errors come from Build(). This builder also enables ticket caching without enabling cookies.

ByteCapacity(bytes), Brotli(quality) and EvictionPolicy(policy) override storage behavior. A zero byte capacity disables that bound; Brotli -1 disables compression. Shared(false) gives Firefox separate TCP and QUIC budgets. Explicit per-transport policy settings also select independent caches; Shared(true) requires a common Both() policy and compatible profile defaults. Firefox's default uses a shared cache with separate protocol key namespaces:

client := surf.NewClient().Builder().
    Impersonate().Firefox().
    SessionCache().
        Both().ByteCapacity(8 << 20).Brotli(1).
        EvictionPolicy(surf.SessionCacheEvictEarliestExpiry).
        Shared(true).Set().
    Build().Unwrap()

Custom(cache) accepts a standard tls.ClientSessionCache whose own policy takes precedence; Custom(nil) disables caching for the selected protocols. TLSConfig.SessionTicketsDisabled still takes precedence over every cache. TCP uses a tcp: key namespace to keep its state separate from QUIC even when both protocols share an application cache. The supplied cache is also used by browser TCP fingerprints through Surf's public TLS serialization bridge.

Firefox's QUIC profile restores a usable ticket's negotiated version and its measured RTT in whole milliseconds. QUICSettings().ResumeRTT(0).Set() disables that estimate independently of session resumption. Chrome keeps its configured version policy and separate per-origin RTT history. See the working browser behavior inventory for implementation scopes, source references and evidence still needed, and the ticket-cache example.

// Set cookies
cookies := []*http.Cookie{
    {Name: "session", Value: "abc123"},
    {Name: "preference", Value: "dark_mode"},
}

resp := surf.NewClient().
    Get("https://example.com").
    AddCookies(cookies...).
    Do()

// Get cookies from response
if resp.IsOk() {
    for _, cookie := range resp.Ok().Cookies {
        fmt.Printf("Cookie: %s = %s\n", cookie.Name, cookie.Value)
    }
}

πŸ“Š Response Handling

Status Code Checking

resp := surf.NewClient().Get("https://api.example.com/data").Do()

if resp.IsOk() {
    switch {
    case resp.Ok().StatusCode.IsSuccess():
        fmt.Println("Success!")
    case resp.Ok().StatusCode.IsRedirection():
        fmt.Println("Redirected to:", resp.Ok().Location())
    case resp.Ok().StatusCode.IsClientError():
        fmt.Println("Client error:", resp.Ok().StatusCode)
    case resp.Ok().StatusCode.IsServerError():
        fmt.Println("Server error:", resp.Ok().StatusCode)
    }
}

Body Processing

resp := surf.NewClient().Get("https://example.com/data").Do()
if resp.IsOk() {
    body := resp.Ok().Body

    // As string (returns g.Result[g.String])
    if content := body.String(); content.IsOk() {
        fmt.Println(content.Ok())
    }

    // As bytes (returns g.Result[g.Bytes])
    if data := body.Bytes(); data.IsOk() {
        fmt.Println(len(data.Ok()))
    }

    // UTF-8 conversion (returns g.Result[g.String])
    if utf8Content := body.UTF8(); utf8Content.IsOk() {
        fmt.Println(utf8Content.Ok())
    }

    // Check content
    if body.Contains("success") {
        fmt.Println("Request succeeded!")
    }

    // Save to file
    err := body.Dump("response.html")
}

Streaming Request Bodies

Use StreamingBody(reader) to send a body without buffering it until EOF. Pass an optional known length; omitted or -1 means unknown, while zero means empty. Surf owns the reader and closes it. A blocking reader must provide a Close method that unblocks Read. A direct stream is sent once; status retries are suppressed and 307/308 redirects are returned without replaying the body.

Use a factory when retries, redirects or HTTP/3 fallback must reopen the source:

response := client.Post("https://example.com/upload").
    StreamingBodyFactory(func() (io.ReadCloser, error) {
        return os.Open("upload.bin")
    }).Do()

The factory runs when sending, returns a fresh reader per attempt and owns no shared cursor. See the streaming upload example.

Streaming Large Responses

resp := surf.NewClient().Get("https://example.com/large-file").Do()
if resp.IsOk() {
    stream := resp.Ok().Body.Stream()
    defer stream.Close()

    scanner := bufio.NewScanner(stream)
    for scanner.Scan() {
        fmt.Println(scanner.Text())
    }
}

Server-Sent Events (SSE)

resp := surf.NewClient().Get("https://example.com/events").Do()
if resp.IsOk() {
    resp.Ok().Body.SSE(func(event *sse.Event) bool {
        fmt.Printf("Event: %s, Data: %s\n", event.Event, event.Data)
        return true  // Continue reading (false to stop)
    })
}

πŸ” Debugging

Request/Response Debugging

resp := surf.NewClient().
    Get("https://api.example.com").
    Do()

if resp.IsOk() {
    resp.Ok().Debug().
        Request().      // Show request details
        Response(true). // Show response with body
        Print()
}

TLS Information

resp := surf.NewClient().Get("https://example.com").Do()
if resp.IsOk() {
    if tlsInfo := resp.Ok().TLSGrabber(); tlsInfo != nil {
        fmt.Printf("TLS Version: %s\n", tlsInfo.TLSVersion)
        fmt.Printf("Server Name: %s\n", tlsInfo.ExtensionServerName)
        fmt.Printf("Fingerprint: %s\n", tlsInfo.FingerprintSHA256)
        fmt.Printf("Common Name: %v\n", tlsInfo.CommonName)
        fmt.Printf("Organization: %v\n", tlsInfo.Organization)
    }
}

⚑ Performance Optimization

Connection Reuse

// Create a reusable client
client := surf.NewClient().
    Builder().
    Impersonate().
    Chrome().
    Build().
    Unwrap()

// Reuse for multiple requests
for i := 0; i < 100; i++ {
    resp := client.Get("https://api.example.com/data").Do()
    // Process response
}

// Clean up when done
defer client.CloseIdleConnections()

Response Caching

client := surf.NewClient().
    Builder().
    CacheBody().      // Enable body caching
    Build().
    Unwrap()

resp := client.Get("https://api.example.com/data").Do()
if resp.IsOk() {
    // First access reads from network
    data1 := resp.Ok().Body.Bytes().Unwrap()

    // Subsequent accesses use cache
    data2 := resp.Ok().Body.Bytes().Unwrap()  // No network I/O
}

Retry Configuration

client := surf.NewClient().
    Builder().
    Retry(3, 2*time.Second).           // Max 3 retries, 2 second wait
    Build().
    Unwrap()

🌐 Advanced Features

H2C (HTTP/2 Cleartext)

// Enable HTTP/2 without TLS
client := surf.NewClient().
    Builder().
    H2C().
    Build().
    Unwrap()

resp := client.Get("http://localhost:8080/h2c-endpoint").Do()

Custom Headers Order

// Control exact header order for fingerprinting evasion
headers := g.NewMapOrd[g.String, g.String]()
headers.Insert("User-Agent", "Custom/1.0")
headers.Insert("Accept", "*/*")
headers.Insert("Accept-Language", "en-US")
headers.Insert("Accept-Encoding", "gzip, deflate")

client := surf.NewClient().
    Builder().
    SetHeaders(headers).  // Headers will be sent in this exact order
    Build().
    Unwrap()

Custom DNS Resolver

client := surf.NewClient().
    Builder().
    DNS("8.8.8.8:53").  // Use Google DNS
    Build().
    Unwrap()

DNS-over-TLS

client := surf.NewClient().
    Builder().
    DNSOverTLS().Cloudflare().  // Cloudflare DoT
    Build().
    Unwrap()

Unix Domain Sockets

client := surf.NewClient().
    Builder().
    UnixSocket("/var/run/docker.sock").
    Build().
    Unwrap()

resp := client.Get("http://localhost/v1.41/containers/json").Do()

Network Changes

Chrome desktop/Android and Firefox desktop profiles react to native address/link changes automatically. Their policies remain distinct: Chrome keeps healthy QUIC, while Firefox retires old multiplexed sessions and preserves active responses and TLS tickets.

client := surf.NewClient().Builder().Impersonate().Windows().Firefox().
    NetworkSettings().Automatic(false).Set().Build().Unwrap()
defer client.Close()

// For an application that already owns OS network notifications:
client.NetworkChanged(surf.NetworkChangeInfo{AddressChanged: true})

NetworkSettings().CoalescingDelay(...).Policy(...).Set() exposes the same controls used by profiles. Explicit overrides apply after profile defaults. Firefox on Linux also observes Ethernet gateway identity, including the next hop selected by its IPv4/IPv6 route checks. Known-MAC replacement and unrelated ARP do not trigger maintenance. NetworkSettings().Identity(reader).Set() overrides the local identity reader; nil disables it. The reader receives nil for a full refresh or numeric neighbors acquiring a previously unknown MAC. The first successful result is a baseline, errors retain it, and later changes set NetworkChangeInfo.IdentityChanged. It must return promptly, be safe across clients and not reenter the client. Identity values stay local; kernel route checks send no IP packets and do not use or replace configured DNS/DoT. See the network-change audit for source references, tests, capture provenance and remaining scope.

Network Interface Binding

client := surf.NewClient().
    Builder().
    InterfaceAddr("192.168.1.100").  // Bind to specific IP
    Build().
    Unwrap()

Raw HTTP Requests

rawRequest := `GET /api/data HTTP/1.1
Host: example.com
User-Agent: Custom/1.0
Accept: application/json

`

resp := surf.NewClient().
    Raw(g.String(rawRequest), "https").
    Do()

πŸ“š API Reference

Client Methods

Method Description
NewClient() Creates a new HTTP client with defaults
Get(url) Creates a GET request
Post(url) Creates a POST request
Put(url) Creates a PUT request
Patch(url) Creates a PATCH request
Delete(url) Creates a DELETE request
Head(url) Creates a HEAD request
Options(url) Creates an OPTIONS request
Connect(url) Creates a CONNECT request
Trace(url) Creates a TRACE request
Raw(raw, scheme) Creates a request from raw HTTP
Builder() Returns a new Builder for client configuration
Std() Convert to standard *net/http.Client
CloseIdleConnections() Closes idle connections while keeping client usable
NetworkChanged(changes...) Apply the built network policy for an application-owned notification
Close() Completely shuts down the client and releases all resources

Builder Methods

Method Description
Impersonate() Enable browser impersonation
JA() Configure JA3/JA4 fingerprinting
HTTP2Settings() Configure HTTP/2 parameters
HTTP3Settings() Configure HTTP/3 parameters
NetworkSettings() Configure native network notifications and profile policy overrides
H2C() Enable HTTP/2 cleartext
Proxy(proxy) Set proxy configuration
DNS(dns) Set custom DNS resolver
DNSOverTLS() Configure DNS-over-TLS
Session() Enable cookie jar for sessions
Timeout(duration) Set request timeout
MaxRedirects(n) Set maximum redirects
NotFollowRedirects() Disable redirect following
FollowOnlyHostRedirects() Only follow same-host redirects
ForwardHeadersOnRedirect() Forward headers on redirects
RedirectPolicy(fn) Custom redirect policy function
Retry(max, wait, codes...) Configure retry logic
CacheBody() Enable response body caching
With(middleware, priority...) Add middleware
BasicAuth(auth) Set basic authentication
BearerAuth(token) Set bearer token authentication
UserAgent(ua) Set custom user agent
SetHeaders(headers...) Set request headers
AddHeaders(headers...) Add request headers
AddCookies(cookies...) Add cookies
WithContext(ctx) Add context
ContentType(type) Set content type
GetRemoteAddress() Track remote address
DisableKeepAlive() Disable keep-alive
DisableCompression() Disable compression
ForceHTTP1() Force HTTP/1.1
ForceHTTP2() Force HTTP/2
ForceHTTP3() Force HTTP/3
UnixSocket(path) Use Unix socket
InterfaceAddr(addr) Bind to network interface
Boundary(fn) Custom multipart boundary generator

Request Methods

Method Description
Do() Execute the request
WithContext(ctx) Add context to request
Body(data) Set request body (JSON, form data, bytes, string, io.Reader)
StreamingBody(reader, length...) Send a reader without buffering; optional length
StreamingBodyFactory(factory, length...) Open a fresh streaming reader for each attempt
SetHeaders(headers...) Set request headers
AddHeaders(headers...) Add request headers
AddCookies(cookies...) Add cookies to request
Multipart(mp) Set multipart form data for request
GetRequest() Returns underlying *http.Request

Multipart Methods

Method Description
NewMultipart() Creates a new Multipart builder
Field(name, value) Adds a form field
File(fieldName, file) Adds a file from *g.File
FileReader(fieldName, fileName, reader) Adds a file from io.Reader
FileString(fieldName, fileName, content) Adds a file from string content
FileBytes(fieldName, fileName, data) Adds a file from byte slice
ContentType(ct) Sets custom Content-Type for the last added file
FileName(name) Overrides filename for the last added file
Retry() Buffers multipart body for retry support

Response Properties

Property Type Description
StatusCode StatusCode HTTP status code
Headers Headers Response headers
Cookies Cookies Response cookies
Body *Body Response body
URL *url.URL Final URL after redirects
Time time.Duration Request duration
ContentLength int64 Content length
Proto string HTTP protocol version
Attempts int Number of retry attempts

Response Methods

Method Description
Debug() Returns debug info for request/response inspection
Location() Returns the Location header (redirect URL)
TLSGrabber() Returns TLS connection information
Referer() Returns HTTP Referer header from original request
GetResponse() Returns underlying *http.Response
GetCookies(url) Returns cookies for a specific URL
SetCookies(url, cookies) Stores cookies in client's cookie jar
RemoteAddress() Returns remote server address

Body Methods

Method Description
String() Get body as string (returns g.Result[g.String])
Bytes() Get body as bytes (returns g.Result[g.Bytes])
JSON(v) Decode JSON into struct
XML(v) Decode XML into struct
UTF8() Convert to UTF-8 (returns g.Result[g.String])
Stream() Get StreamReader for streaming (with Close support)
SSE(fn) Process Server-Sent Events
Dump(file) Save to file
Contains(pattern) Check if contains pattern
Limit(n) Limit body size
WithContext(ctx) Set context for cancellation of read operations
Close() Close body reader

🀝 Contributing

The root surf package owns the public client, builders, settings, callbacks and adapters. Keep their names, signatures and import paths stable when moving code. GetTLSConfig() and GetDialer() retain their shared configuration pointers.

Location Responsibility
http2_settings.go HTTP/2 settings, HPACK and receive-window policy
http3_settings.go, http3_qpack.go Public HTTP/3 types and fluent configuration
quic_settings.go Public QUIC types and fluent configuration
internal/http3 HTTP/3 transport, DNS/discovery, ECH, protocol fallback and private tests
internal/quic UDP ownership, QUIC dialing, SOCKS relay, address racing and private tests
internal/connrace Shared connection preparation, cancellation and policy history, with private tests
internal/quictls, internal/tlsstate, internal/specclone TLS integration, state conversion and template cloning
internal/drainbody, internal/retryafter Body cleanup and Retry-After parsing
profiles/, header/, pkg/ Existing public profiles, header constants and supporting packages
tests/ Public API and wire behavior; internal tests stay with their implementation

Public record types remain defined in surf; custom HTTPS lookups cross the internal boundary through a checked struct conversion. Builders retain their existing methods and return types. Browser policies remain in profiles/; library refactoring preserves their wire fixtures and the coverage package list in CI.

Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

❀️ Support / Sponsorship

If you enjoy Surf and want to help keep development going, you can support the project with crypto donations:

USDT TON SOL BTC ETH

Thank you for your support!

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ™ Acknowledgments

πŸ“ž Support

Made with ❀️ by the Surf contributors

Documentation ΒΆ

Overview ΒΆ

Package surf provides a comprehensive HTTP client library with advanced features for web scraping, automation, and HTTP/3 support with various browser fingerprinting capabilities.

Index ΒΆ

Constants ΒΆ

View Source
const (
	HPACKDefault              = http2.HPACKDefault
	HPACKWithoutIndexing      = http2.HPACKWithoutIndexing
	HPACKNeverIndex           = http2.HPACKNeverIndex
	HPACKIncrementalIndexing  = http2.HPACKIncrementalIndexing
	HPACKHuffmanDefault       = http2.HPACKHuffmanDefault
	HPACKHuffmanAlways        = http2.HPACKHuffmanAlways
	HPACKHuffmanNever         = http2.HPACKHuffmanNever
	HPACKNameReferenceDefault = http2.HPACKNameReferenceDefault
	HPACKNameReferenceLast    = http2.HPACKNameReferenceLast
	HPACKNameReferenceFirst   = http2.HPACKNameReferenceFirst
)
View Source
const (
	QPACKEncoderStream = http3.QPACKEncoderStream
	QPACKDecoderStream = http3.QPACKDecoderStream
)
View Source
const (
	QPACKCapacityOnSettings    = http3.QPACKCapacityOnSettings
	QPACKCapacityBeforeHeaders = http3.QPACKCapacityBeforeHeaders
)
View Source
const (
	QPACKHuffmanDefault = http3.QPACKHuffmanDefault
	QPACKHuffmanAuto    = http3.QPACKHuffmanAuto
	QPACKHuffmanAlways  = http3.QPACKHuffmanAlways
	QPACKHuffmanNever   = http3.QPACKHuffmanNever
	QPACKIndexAll       = http3.QPACKIndexAll
	QPACKIndexNewNames  = http3.QPACKIndexNewNames
	QPACKIndexNone      = http3.QPACKIndexNone
)
View Source
const (
	SETTINGS_QPACK_MAX_TABLE_CAPACITY = h3transport.SETTINGS_QPACK_MAX_TABLE_CAPACITY
	SETTINGS_MAX_FIELD_SECTION_SIZE   = h3transport.SETTINGS_MAX_FIELD_SECTION_SIZE
	SETTINGS_QPACK_BLOCKED_STREAMS    = h3transport.SETTINGS_QPACK_BLOCKED_STREAMS
	SETTINGS_ENABLE_CONNECT_PROTOCOL  = h3transport.SETTINGS_ENABLE_CONNECT_PROTOCOL
	SETTINGS_H3_DATAGRAM              = h3transport.SETTINGS_H3_DATAGRAM
	H3_DATAGRAM                       = h3transport.H3_DATAGRAM
	SETTINGS_ENABLE_WEBTRANSPORT      = h3transport.SETTINGS_ENABLE_WEBTRANSPORT
)

HTTP/3 SETTINGS frame parameter identifiers as defined in RFC 9114.

View Source
const (
	InitialPaddingPacket   = quic.InitialPaddingPacket
	InitialPaddingDatagram = quic.InitialPaddingDatagram
)
View Source
const (
	AckReorderingNative    = quic.AckReorderingNative
	AckReorderingImmediate = quic.AckReorderingImmediate
	AckReorderingWindow    = quic.AckReorderingWindow
	AckECNNative           = quic.AckECNNative
	AckECNTransitions      = quic.AckECNTransitions
	AckECNCountOnly        = quic.AckECNCountOnly
)
View Source
const (
	CongestionControlNative     = quic.CongestionControlNative
	CongestionControlReno       = quic.CongestionControlReno
	CongestionControlCubic      = quic.CongestionControlCubic
	CongestionControlCubicBytes = quic.CongestionControlCubicBytes
	SlowStartNative             = quic.SlowStartNative
	SlowStartClassic            = quic.SlowStartClassic
	SlowStartHybrid             = quic.SlowStartHybrid
)
View Source
const (
	PacingNative      = quic.PacingNative
	PacingLeakyBucket = quic.PacingLeakyBucket
	PacingScheduled   = quic.PacingScheduled
)
View Source
const (
	// SessionTicketNewestFirst selects the most recently received ticket.
	SessionTicketNewestFirst = tlscache.NewestFirst
	// SessionTicketEarliestExpiryFirst selects the nearest expiry, with new equal-expiry tickets first.
	SessionTicketEarliestExpiryFirst = tlscache.EarliestExpiryFirst
	// SessionCacheEvictLeastRecentlyUsed removes the least recently accessed key.
	SessionCacheEvictLeastRecentlyUsed = tlscache.EvictLeastRecentlyUsed
	// SessionCacheEvictEarliestExpiry removes individual tickets nearest expiration.
	SessionCacheEvictEarliestExpiry = tlscache.EvictEarliestExpiry
)

Variables ΒΆ

This section is empty.

Functions ΒΆ

This section is empty.

Types ΒΆ

type AckECNMode ΒΆ

type AckECNMode = quic.AckECNMode

type AckReorderingMode ΒΆ

type AckReorderingMode = quic.AckReorderingMode

type AlternativeServiceBackoff ΒΆ

type AlternativeServiceBackoff = func(consecutiveFailures uint32) time.Duration

type Body ΒΆ

type Body struct {

	// Underlying body reader (usually http.Response.Body).
	// Provides access to the raw response stream.
	Reader io.ReadCloser
	// contains filtered or unexported fields
}

Body represents an HTTP response body with enhanced functionality and automatic caching. Provides convenient methods for parsing common data formats (JSON, XML, text) and includes features like automatic decompression, content caching, character set detection, and size limits.

func (*Body) Bytes ΒΆ

func (b *Body) Bytes() g.Result[g.Bytes]

Bytes returns the body's content as a byte slice.

func (*Body) Close ΒΆ

func (b *Body) Close() error

Close closes the body and returns any error encountered. It drains remaining data for connection reuse, but respects context cancellation.

func (*Body) Contains ΒΆ

func (b *Body) Contains(pattern any) bool

Contains checks if the body's content contains the provided pattern (byte slice, string, or *regexp.Regexp) and returns a boolean.

func (*Body) Dump ΒΆ

func (b *Body) Dump(filename g.String) error

Dump dumps the body's content to a file with the given filename.

func (*Body) JSON ΒΆ

func (b *Body) JSON(data any) error

JSON decodes the body's content as JSON into the provided data structure.

func (*Body) Limit ΒΆ

func (b *Body) Limit(limit int64) *Body

Limit sets the body's size limit and returns the modified body.

func (*Body) SSE ΒΆ

func (b *Body) SSE(fn func(event *sse.Event) bool) error

SSE reads the body's content as Server-Sent Events (SSE) and calls the provided function for each event. It expects the function to take an *sse.Event pointer as its argument and return a boolean value. If the function returns false, the SSE reading stops.

func (*Body) Stream ΒΆ

func (b *Body) Stream() *StreamReader

Stream returns a bufio.Reader for streaming the body content. IMPORTANT: Call this method once and reuse the returned reader. Each call creates a new bufio.Reader; calling repeatedly in a loop will lose buffered data.

func (*Body) String ΒΆ

func (b *Body) String() g.Result[g.String]

String returns the body's content as a g.String.

func (*Body) UTF8 ΒΆ

func (b *Body) UTF8() g.Result[g.String]

UTF8 converts the body's content to UTF-8 encoding and returns it as a string.

func (*Body) WithContext ΒΆ

func (b *Body) WithContext(ctx context.Context) *Body

WithContext sets the context for cancellation of read operations.

Must be called BEFORE reading the body (Bytes(), String(), Stream(), etc.). Silently ignored if reading has already started.

func (*Body) XML ΒΆ

func (b *Body) XML(data any) error

XML decodes the body's content as XML into the provided data structure.

type Builder ΒΆ

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

Builder provides a fluent interface for configuring HTTP clients with various advanced features including proxy settings, TLS fingerprinting, HTTP/2 and HTTP/3 support, retry logic, redirect handling, and browser impersonation capabilities.

func (*Builder) AddCookies ΒΆ

func (b *Builder) AddCookies(cookies ...*http.Cookie) *Builder

AddCookies adds cookies to the request.

func (*Builder) AddHeaders ΒΆ

func (b *Builder) AddHeaders(headers ...any) *Builder

AddHeaders adds headers to the request, appending to any existing headers with the same name.

func (*Builder) BasicAuth ΒΆ

func (b *Builder) BasicAuth(authentication g.String) *Builder

BasicAuth sets the basic authentication credentials for the client.

func (*Builder) BearerAuth ΒΆ

func (b *Builder) BearerAuth(authentication g.String) *Builder

BearerAuth sets the bearer token for the client.

func (*Builder) Boundary ΒΆ

func (b *Builder) Boundary(boundary func() g.String) *Builder

func (*Builder) Build ΒΆ

func (b *Builder) Build() g.Result[*Client]

Build applies all configured settings and returns the client. Returns g.Result with error if any middleware fails.

func (*Builder) CacheBody ΒΆ

func (b *Builder) CacheBody() *Builder

CacheBody configures whether the client should cache the body of the response.

func (*Builder) CertificateIntermediates ΒΆ

func (b *Builder) CertificateIntermediates(pool *x509.CertPool) *Builder

CertificateIntermediates supplies untrusted issuer candidates for JA-enabled TCP and HTTP/3 certificate verification. The caller's configured roots still decide trust. Chrome presets supply candidates for advertised Trust Anchor IDs. The pool is copied; later builder changes affect future builds. Nil clears it.

func (*Builder) ClientHints ΒΆ

func (b *Builder) ClientHints() *ClientHints

ClientHints opens the client-hint sub-builder. Browser defaults are applied first and explicit settings last, independent of configuration call order.

func (*Builder) ContentType ΒΆ

func (b *Builder) ContentType(contentType g.String) *Builder

ContentType sets the content type for the client.

func (*Builder) DNS ΒΆ

func (b *Builder) DNS(dns g.String) *Builder

DNS sets the custom DNS resolver address.

func (*Builder) DNSOverTLS ΒΆ

func (b *Builder) DNSOverTLS() *DNSOverTLS

DNSOverTLS configures the client to use DNS over TLS.

func (*Builder) DisableCompression ΒΆ

func (b *Builder) DisableCompression() *Builder

DisableCompression disables automatic response body decompression.

func (*Builder) DisableKeepAlive ΒΆ

func (b *Builder) DisableKeepAlive() *Builder

DisableKeepAlive disable keep-alive connections.

func (*Builder) FollowOnlyHostRedirects ΒΆ

func (b *Builder) FollowOnlyHostRedirects() *Builder

FollowOnlyHostRedirects configures whether the client should only follow redirects within the same host.

func (*Builder) ForceHTTP1 ΒΆ

func (b *Builder) ForceHTTP1() *Builder

ForceHTTP1 configures the client to use HTTP/1.1 forcefully.

func (*Builder) ForceHTTP2 ΒΆ

func (b *Builder) ForceHTTP2() *Builder

ForceHTTP2 configures the client to use HTTP/2 forcefully.

func (*Builder) ForceHTTP3 ΒΆ

func (b *Builder) ForceHTTP3() *Builder

ForceHTTP3 attempts HTTP/3 directly, without requiring Alt-Svc or HTTPS DNS. An unavailable UDP path or a TCP-only proxy can still select HTTP/2 or HTTP/1. Enabled discovery still obtains HTTPS DNS metadata, including ECHConfig.

func (*Builder) ForwardHeadersOnRedirect ΒΆ

func (b *Builder) ForwardHeadersOnRedirect() *Builder

ForwardHeadersOnRedirect adds a middleware to the ClientBuilder object that ensures HTTP headers are forwarded during a redirect.

func (*Builder) GetRemoteAddress ΒΆ

func (b *Builder) GetRemoteAddress() *Builder

GetRemoteAddress configures whether the client should get the remote address.

func (*Builder) H2C ΒΆ

func (b *Builder) H2C() *Builder

H2C configures the client to handle HTTP/2 Cleartext (h2c).

func (*Builder) HTTP1Settings ΒΆ

func (b *Builder) HTTP1Settings() *HTTP1Settings

HTTP1Settings starts the nested HTTP/1 request-writing builder.

func (*Builder) HTTP2Settings ΒΆ

func (b *Builder) HTTP2Settings() *HTTP2Settings

HTTP2Settings configures settings related to HTTP/2 and returns an http2s struct.

func (*Builder) HTTP3Settings ΒΆ

func (b *Builder) HTTP3Settings() *HTTP3Settings

HTTP3Settings configures settings related to HTTP/3 and returns an http3s struct.

func (*Builder) Impersonate ΒΆ

func (b *Builder) Impersonate() *Impersonate

Impersonate configures something related to impersonation and returns an impersonate struct.

func (*Builder) InterfaceAddr ΒΆ

func (b *Builder) InterfaceAddr(address g.String) *Builder

InterfaceAddr sets the local network interface for outbound connections. Accepts either an IP address (e.g., "192.168.1.100", "::1") or an interface name (e.g., "eth0", "en0").

func (*Builder) JA ΒΆ

func (b *Builder) JA() *JA

JA configures the client to use a specific TLS fingerprint.

func (*Builder) MaxRedirects ΒΆ

func (b *Builder) MaxRedirects(maxRedirects int) *Builder

MaxRedirects sets the maximum number of redirects the client should follow.

func (*Builder) NetworkSettings ΒΆ

func (b *Builder) NetworkSettings() *NetworkSettings

NetworkSettings starts the nested network-notification builder. Plain clients have no automatic subscription; browser profiles provide their own policy.

func (*Builder) NotFollowRedirects ΒΆ

func (b *Builder) NotFollowRedirects() *Builder

NotFollowRedirects disables following redirects for the client.

func (*Builder) Proxy ΒΆ

func (b *Builder) Proxy(proxy g.String) *Builder

Proxy sets the proxy URL for the client.

func (*Builder) QUICSettings ΒΆ

func (b *Builder) QUICSettings() *QUICSettings

QUICSettings configures the QUIC transport used by HTTP/3. Set returns this Builder, as with HTTP2Settings and HTTP3Settings.

func (*Builder) RedirectPolicy ΒΆ

func (b *Builder) RedirectPolicy(fn func(*http.Request, []*http.Request) error) *Builder

RedirectPolicy sets a custom redirect policy for the client.

func (*Builder) Retry ΒΆ

func (b *Builder) Retry(retryMax int, retryWait time.Duration, codes ...int) *Builder

Retry configures the retry behavior of the client.

Parameters:

retryMax:  Maximum number of retry attempts. If zero or negative the
           retry loop is disabled.
retryWait: Minimum wait between retries. If the server responds with a
           Retry-After header on a retryable status, the actual pause
           becomes max(retryWait, Retry-After). Both legal forms are
           honoured: integer delay-seconds and HTTP-date (IMF-fixdate,
           RFC 850, ANSI C asctime). Absent or malformed values fall
           back to retryWait.
codes:     Optional list of HTTP status codes that trigger retries.
           If no codes are provided, the defaults are used
           (500 Internal Server Error, 429 Too Many Requests,
           503 Service Unavailable).

Upper bound for the entire retry cycle, including a long Retry-After sleep, is the request context deadline β€” set it with Request.WithContext(ctxWithDeadline). Builder.Timeout only bounds a single cli.Do invocation (connect + transmission + body read); it does not interrupt the sleep between retries.

func (*Builder) SecureTLS ΒΆ

func (b *Builder) SecureTLS() *Builder

SecureTLS enables TLS certificate verification. By default surf skips certificate verification (InsecureSkipVerify=true). Call this for production use where certificate validation is required.

func (*Builder) Session ΒΆ

func (b *Builder) Session() *Builder

Session configures whether the client should maintain a session.

func (*Builder) SessionCache ΒΆ

func (b *Builder) SessionCache() *SessionCache

SessionCache starts the nested ticket-cache builder. Browser defaults are applied first, followed by explicit settings, regardless of chain order. Each call selects both transports; TCP and QUIC narrow subsequent settings.

func (*Builder) SetHeaders ΒΆ

func (b *Builder) SetHeaders(headers ...any) *Builder

SetHeaders sets headers for the request, replacing existing ones with the same name.

func (Builder) String ΒΆ

func (b Builder) String() string

String generate a string representation of the ClientBuilder instance.

func (*Builder) TLSConfig ΒΆ

func (b *Builder) TLSConfig(config *tls.Config) *Builder

TLSConfig sets a custom TLS configuration for the client.

func (*Builder) Timeout ΒΆ

func (b *Builder) Timeout(timeout time.Duration) *Builder

Timeout sets the timeout duration for the client.

func (*Builder) UnixSocket ΒΆ

func (b *Builder) UnixSocket(address g.String) *Builder

UnixSocket sets the path for a Unix domain socket. This allows the HTTP client to connect to the server using a Unix domain socket instead of a traditional TCP/IP connection.

func (*Builder) UserAgent ΒΆ

func (b *Builder) UserAgent(userAgent any) *Builder

UserAgent sets the user agent for the client.

func (*Builder) WebSocketGuard ΒΆ

func (b *Builder) WebSocketGuard() *Builder

WebSocketGuard enables middleware that blocks WebSocket upgrade responses (HTTP 101). Without this, surf allows 101 Switching Protocols to pass through β€” compatible with websocket.Dial and other WebSocket libraries that use surf.Std() as HTTPClient. Enable this only if you want to explicitly reject unexpected WebSocket upgrades.

func (*Builder) With ΒΆ

func (b *Builder) With(middleware any, priority ...int) *Builder

With registers middleware into the client builder with optional priority.

It accepts one of the following middleware function types:

  • func(*surf.Client) error β€” client middleware, modifies or initializes the client
  • func(*surf.Request) error β€” request middleware, intercepts or transforms outgoing requests
  • func(*surf.Response) error β€” response middleware, intercepts or transforms incoming responses

Parameters:

  • middleware: A function matching one of the supported middleware types.
  • priority (optional): Integer priority level. Lower values run earlier. Defaults to 0.

Middleware with the same priority are executed in order of insertion (FIFO). If the middleware type is not recognized, With panics with an informative error.

Example:

// Adding client middleware to modify client settings.
.With(func(client *surf.Client) error {
    // Custom logic to modify the client settings.
    return nil
})

// Adding request middleware to intercept outgoing requests.
.With(func(req *surf.Request) error {
    // Custom logic to modify outgoing requests.
    return nil
})

// Adding response middleware to intercept incoming responses.
.With(func(resp *surf.Response) error {
    // Custom logic to handle incoming responses.
    return nil
})

Note: Ensure that middleware functions adhere to the specified function signatures to work correctly with the With method.

func (*Builder) WithContext ΒΆ

func (b *Builder) WithContext(ctx context.Context) *Builder

WithContext associates the provided context with the request.

type Client ΒΆ

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

Client represents a highly configurable HTTP client with middleware support, advanced transport options (HTTP/1.1, HTTP/2, HTTP/3), proxy handling, TLS fingerprinting, and comprehensive request/response processing capabilities.

func NewClient ΒΆ

func NewClient() *Client

NewClient creates a new Client with sensible default settings including default dialer, TLS configuration, HTTP transport, and basic middleware.

func (*Client) Builder ΒΆ

func (c *Client) Builder() *Builder

Builder returns a new Builder instance associated with this client. The builder allows for method chaining to configure various client options.

func (*Client) ClearClientHints ΒΆ

func (c *Client) ClearClientHints()

ClearClientHints clears learned origin opt-ins without closing connections or changing configured metadata. It is safe alongside concurrent requests.

func (*Client) ClientHintNames ΒΆ

func (c *Client) ClientHintNames(rawURL g.String) []string

ClientHintNames returns a copy of the remembered opt-in names for a URL's origin. It reports no opt-ins when negotiation is not installed.

func (*Client) Close ΒΆ

func (c *Client) Close() error

Close completely shuts down the client and releases all resources. After calling Close, the client should not be used.

func (*Client) CloseIdleConnections ΒΆ

func (c *Client) CloseIdleConnections()

CloseIdleConnections closes idle connections while keeping the client usable. Safe to call periodically to free resources during long-running operations.

func (*Client) Connect ΒΆ

func (c *Client) Connect(rawURL g.String) *Request

Connect creates a new HTTP CONNECT request for the specified URL. CONNECT requests are used to establish a tunnel to the server.

func (*Client) Delete ΒΆ

func (c *Client) Delete(rawURL g.String) *Request

Delete creates a new HTTP DELETE request for the specified URL. DELETE requests are used to remove a resource from a server.

func (*Client) Get ΒΆ

func (c *Client) Get(rawURL g.String) *Request

Get creates a new HTTP GET request for the specified URL. GET requests are used to retrieve data from a server.

func (*Client) GetClient ΒΆ

func (c *Client) GetClient() *http.Client

GetClient returns http.Client used by the Client.

func (*Client) GetDialer ΒΆ

func (c *Client) GetDialer() *net.Dialer

GetDialer returns the net.Dialer used by the Client.

func (*Client) GetTLSConfig ΒΆ

func (c *Client) GetTLSConfig() *tls.Config

GetTLSConfig returns the tls.Config used by the Client.

func (*Client) GetTransport ΒΆ

func (c *Client) GetTransport() http.RoundTripper

GetTransport returns the http.transport used by the Client.

func (*Client) Head ΒΆ

func (c *Client) Head(rawURL g.String) *Request

Head creates a new HTTP HEAD request for the specified URL. HEAD requests are identical to GET but without the response body.

func (*Client) NetworkChanged ΒΆ

func (c *Client) NetworkChanged(changes ...NetworkChangeInfo)

NetworkChanged immediately applies the built network policy. With no argument it describes a stable address/link/route change. Applications that already own notifications can disable Automatic and call this hook. Native notifications use the configured coalescing delay; explicit calls are already-delivered events.

func (*Client) Options ΒΆ

func (c *Client) Options(rawURL g.String) *Request

Options creates a new HTTP OPTIONS request for the specified URL. OPTIONS requests are used to describe the communication options for a resource.

func (*Client) Patch ΒΆ

func (c *Client) Patch(rawURL g.String) *Request

Patch creates a new HTTP PATCH request for the specified URL. PATCH requests are used to apply partial modifications to a resource.

func (*Client) Post ΒΆ

func (c *Client) Post(rawURL g.String) *Request

Post creates a new HTTP POST request for the specified URL. POST requests are used to submit data to a server.

func (*Client) Put ΒΆ

func (c *Client) Put(rawURL g.String) *Request

Put creates a new HTTP PUT request for the specified URL. PUT requests are used to replace a resource on a server.

func (*Client) Raw ΒΆ

func (c *Client) Raw(raw, scheme g.String) *Request

Raw creates a new HTTP request using the provided raw data and scheme. The raw parameter should contain the raw HTTP request data as a string. The scheme parameter specifies the scheme (e.g., http, https) for the request.

func (*Client) Std ΒΆ

func (c *Client) Std() *_http.Client

Std returns a standard net/http.Client that wraps the configured surf client. This is useful for integrating with third-party libraries that expect a standard net/http.Client while preserving most surf features.

Supported features:

  • JA3/TLS fingerprinting
  • HTTP/2 settings
  • Cookies and sessions
  • Request/Response middleware
  • Headers (User-Agent, custom headers)
  • Proxy configuration
  • Timeout settings
  • Redirect policies
  • Impersonate browser headers

Known limitations:

  • Retry logic is NOT supported (implemented in Request.Do(), not in transport)
  • Response body caching is NOT supported
  • Remote address tracking is NOT supported
  • Request timing information is NOT available

For applications requiring retry logic, consider implementing it at the application level or use surf.Client directly for those specific requests.

Example usage:

surfClient := surf.NewClient().
	Builder().
	JA3().Chrome().
	Session().
	Build()

// For libraries expecting net/http.Client
stdClient := surfClient.Std()

botClient := &BaseBotClient{
	Client: *stdClient,
}

func (*Client) Trace ΒΆ

func (c *Client) Trace(rawURL g.String) *Request

Trace creates a new HTTP TRACE request for the specified URL. TRACE requests are used to perform a message loop-back test along the path to the target resource.

type ClientHintBrand ΒΆ

type ClientHintBrand struct {
	// Brand is the product name or GREASE brand.
	Brand string
	// Version is the complete version advertised for this brand.
	Version string
}

ClientHintBrand describes one brand in Sec-CH-UA-Full-Version-List.

type ClientHints ΒΆ

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

ClientHints is Surf's fluent configuration for available Client Hints and origin opt-ins. Chrome desktop/Android enable negotiation automatically. Other clients can enable it with Set. Explicit request headers take precedence.

func (*ClientHints) ALPS ΒΆ

func (h *ClientHints) ALPS(value bool) *ClientHints

ALPS applies available hints requested by the selected TLS connection's authenticated ACCEPT_CH instructions. It does not persist them as response opt-ins. Enabled by default with negotiation; protocol SETTINGS remain active.

func (*ClientHints) Architecture ΒΆ

func (h *ClientHints) Architecture(value string) *ClientHints

Architecture sets sec-ch-ua-arch, such as x86 or arm; Android normally uses empty.

func (*ClientHints) Bitness ΒΆ

func (h *ClientHints) Bitness(value string) *ClientHints

Bitness sets sec-ch-ua-bitness, such as 64 or 32; Android normally uses empty.

func (*ClientHints) Capacity ΒΆ

func (h *ClientHints) Capacity(value int) *ClientHints

Capacity bounds remembered origins to 1..1048576; the default is 1024.

func (*ClientHints) ClearSiteData ΒΆ

func (h *ClientHints) ClearSiteData(value bool) *ClientHints

ClearSiteData permits secure response directives to clear this client's remembered hint opt-ins. Clearing directives also suppress same-response Accept-CH/Critical-CH, even when invalidation is disabled or the directive cannot clear storage. This follows Chromium's separate parsed-header gate. It does not clear cookies, HTTP cache or storage. Enabled by default with negotiation. Surf has no DOM credential/storage context; applications can disable this client-local invalidation when applying their own context policy.

func (*ClientHints) Clock ΒΆ

func (h *ClientHints) Clock(value func() time.Time) *ClientHints

Clock supplies origin-cache time and must support concurrent calls. Nil restores time.Now.

func (*ClientHints) Enabled ΒΆ

func (h *ClientHints) Enabled(value bool) *ClientHints

Enabled controls negotiation and emission of learned hints. Explicit request headers, including the profile's static low-entropy fields, remain caller-owned.

func (*ClientHints) FormFactors ΒΆ

func (h *ClientHints) FormFactors(values ...string) *ClientHints

FormFactors supplies ordered form-factor strings, such as Desktop or Mobile.

func (*ClientHints) FullVersion ΒΆ

func (h *ClientHints) FullVersion(value string) *ClientHints

FullVersion sets the complete browser version and updates matching product entries in its full-version list, leaving the GREASE version independent.

func (*ClientHints) FullVersionList ΒΆ

func (h *ClientHints) FullVersionList(values ...ClientHintBrand) *ClientHints

FullVersionList supplies ordered complete product and GREASE versions.

func (*ClientHints) Lifetime ΒΆ

func (h *ClientHints) Lifetime(value time.Duration) *ClientHints

Lifetime bounds opt-in retention. Zero keeps in-memory state for this client.

func (*ClientHints) Model ΒΆ

func (h *ClientHints) Model(value string) *ClientHints

Model sets the device model; desktop Chrome uses an empty model.

func (*ClientHints) PlatformVersion ΒΆ

func (h *ClientHints) PlatformVersion(value string) *ClientHints

PlatformVersion sets the target OS version, independent of the Go host OS.

func (*ClientHints) Set ΒΆ

func (h *ClientHints) Set() *Builder

Set applies the accumulated configuration and returns the ordinary client builder. Invalid names, values or limits are reported by Builder.Build.

func (*ClientHints) Value ΒΆ

func (h *ClientHints) Value(name, value string) *ClientHints

Value supplies a serialized recognized hint value, emitted only when opted in unless Chromium sends that hint by default. Unknown names fail Builder.Build.

func (*ClientHints) WoW64 ΒΆ

func (h *ClientHints) WoW64(value bool) *ClientHints

WoW64 reports a 32-bit Chrome process running on 64-bit Windows.

type CongestionControlAlgorithm ΒΆ

type CongestionControlAlgorithm = quic.CongestionControlAlgorithm

type ConnectionRacingInfo ΒΆ

type ConnectionRacingInfo = profiles.ConnectionRacingInfo

type ConnectionRacingPolicy ΒΆ

type ConnectionRacingPolicy = profiles.ConnectionRacingPolicy

type CookieJarAdapter ΒΆ

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

CookieJarAdapter adapts github.com/alvarorichard/enetx-http.CookieJar to net/http.CookieJar. It provides bidirectional cookie conversion between the two HTTP packages, ensuring cookies set through either interface work correctly.

func (*CookieJarAdapter) Cookies ΒΆ

func (c *CookieJarAdapter) Cookies(u *url.URL) []*_http.Cookie

Cookies implements http.CookieJar interface. It retrieves cookies from the underlying surf cookie jar and converts them to standard net/http cookie format.

func (*CookieJarAdapter) SetCookies ΒΆ

func (c *CookieJarAdapter) SetCookies(u *url.URL, _cookies []*_http.Cookie)

SetCookies implements http.CookieJar interface. It converts standard net/http cookies to enetx/http format and delegates to the underlying surf cookie jar.

type Cookies ΒΆ

type Cookies []*http.Cookie

Cookies represents a list of HTTP Cookies.

func (Cookies) Contains ΒΆ

func (cs Cookies) Contains(pattern any) bool

Contains checks if the cookies collection contains a cookie that matches the provided pattern. The pattern parameter can be either a string or a pointer to a regexp.Regexp object. The method returns true if a matching cookie is found and false otherwise.

type CryptoRange ΒΆ

type CryptoRange = quic.CryptoRange

CryptoRange selects a byte range in the first ClientHello's CRYPTO stream.

type DNSOverTLS ΒΆ

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

DNSOverTLS is a configuration struct for DNS over TLS settings.

func (*DNSOverTLS) AdGuard ΒΆ

func (dot *DNSOverTLS) AdGuard() *Builder

AdGuard sets up DNS over TLS with AdGuard DNS.

func (*DNSOverTLS) AddProvider ΒΆ

func (dot *DNSOverTLS) AddProvider(serverName g.String, addresses ...g.String) *Builder

AddProvider sets up DNS over TLS with a custom DNS provider. It configures a custom net.Resolver using the resolver method.

func (*DNSOverTLS) Ali ΒΆ

func (dot *DNSOverTLS) Ali() *Builder

Ali sets up DNS over TLS with AliDNS.

func (*DNSOverTLS) CIRAShield ΒΆ

func (dot *DNSOverTLS) CIRAShield() *Builder

CIRAShield sets up DNS over TLS with CIRA Canadian Shield DNS.

func (*DNSOverTLS) Cloudflare ΒΆ

func (dot *DNSOverTLS) Cloudflare() *Builder

Cloudflare sets up DNS over TLS with Cloudflare DNS.

func (*DNSOverTLS) Forge ΒΆ

func (dot *DNSOverTLS) Forge() *Builder

Forge sets up DNS over TLS with DNS Forge.

func (*DNSOverTLS) Google ΒΆ

func (dot *DNSOverTLS) Google() *Builder

Google sets up DNS over TLS with Google Public DNS.

func (*DNSOverTLS) LibreDNS ΒΆ

func (dot *DNSOverTLS) LibreDNS() *Builder

LibreDNS sets up DNS over TLS with LibreDNS.

func (*DNSOverTLS) Quad9 ΒΆ

func (dot *DNSOverTLS) Quad9() *Builder

Quad9 sets up DNS over TLS with Quad9 DNS.

func (*DNSOverTLS) Quad101 ΒΆ

func (dot *DNSOverTLS) Quad101() *Builder

Quad101 sets up DNS over TLS with Quad101 DNS.

func (*DNSOverTLS) SB ΒΆ

func (dot *DNSOverTLS) SB() *Builder

SB sets up DNS over TLS with Secure DNS (dot.sb).

func (*DNSOverTLS) Switch ΒΆ

func (dot *DNSOverTLS) Switch() *Builder

Switch sets up DNS over TLS with SWITCH DNS.

type Debug ΒΆ

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

Debug is a struct that holds debugging information for an HTTP response.

func (*Debug) Print ΒΆ

func (d *Debug) Print()

Print prints the debug information.

func (*Debug) Request ΒΆ

func (d *Debug) Request(verbos ...bool) *Debug

Request appends the request details to the debug information.

func (*Debug) Response ΒΆ

func (d *Debug) Response(verbos ...bool) *Debug

Response appends the response details to the debug information.

type EarlyRequestPolicy ΒΆ

type EarlyRequestPolicy = profiles.EarlyRequestPolicy

EarlyRequestPolicy adds a history-based gate to safe HTTP/3 early requests.

type Err101ResponseCode ΒΆ

type Err101ResponseCode struct{ Msg string }

Err101ResponseCode indicates a 101 Switching Protocols response was received. This error is used to handle HTTP 101 responses that require protocol upgrades.

func (*Err101ResponseCode) Error ΒΆ

func (e *Err101ResponseCode) Error() string

type ErrHTTP2Fallback ΒΆ

type ErrHTTP2Fallback struct {
	HTTP2 error
	HTTP1 error
}

ErrHTTP2Fallback indicates that an HTTPS request attempted HTTP/2 first, then tried to fall back to HTTP/1.1, but both attempts failed.

Both underlying errors are accessible via Unwrap, enabling errors.Is and errors.As to match against either the HTTP/2 or HTTP/1.1 failure.

func (*ErrHTTP2Fallback) Error ΒΆ

func (e *ErrHTTP2Fallback) Error() string

func (*ErrHTTP2Fallback) Unwrap ΒΆ

func (e *ErrHTTP2Fallback) Unwrap() []error

type ErrUserAgentType ΒΆ

type ErrUserAgentType struct{ Msg string }

ErrUserAgentType indicates an invalid user agent type was provided. This error is returned when the user agent parameter is not of a supported type (string, g.String, slices, etc.).

func (*ErrUserAgentType) Error ΒΆ

func (e *ErrUserAgentType) Error() string

type ErrWebSocketUpgrade ΒΆ

type ErrWebSocketUpgrade struct{ Msg string }

ErrWebSocketUpgrade indicates that a request received a WebSocket upgrade response. This error is returned when the server responds with HTTP 101 Switching Protocols for WebSocket connections, which require special handling.

func (*ErrWebSocketUpgrade) Error ΒΆ

func (e *ErrWebSocketUpgrade) Error() string

type HPACKHuffmanMode ΒΆ

type HPACKHuffmanMode = http2.HPACKHuffmanMode

HPACKRepresentation selects how a request or trailer field is encoded.

type HPACKNameReferencePolicy ΒΆ

type HPACKNameReferencePolicy = http2.HPACKNameReferencePolicy

HPACKRepresentation selects how a request or trailer field is encoded.

type HPACKRepresentation ΒΆ

type HPACKRepresentation = http2.HPACKRepresentation

HPACKRepresentation selects how a request or trailer field is encoded.

type HTTP1Settings ΒΆ

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

HTTP1Settings configures owned HTTP/1 request buffers and write packing. Browser defaults apply first; explicit fluent overrides apply last.

func (*HTTP1Settings) BodyReadSize ΒΆ

func (h *HTTP1Settings) BodyReadSize(size int) *HTTP1Settings

BodyReadSize bounds body reads, zero through 1 MiB. Zero retains native copy optimizations. Explicit sizes also apply to file and streaming bodies.

func (*HTTP1Settings) HeaderBodyMergeLimit ΒΆ

func (h *HTTP1Settings) HeaderBodyMergeLimit(limit int64) *HTTP1Settings

HeaderBodyMergeLimit selects the largest combined header/in-memory-body write. Zero separates nonempty bodies; the valid range is zero through 1 MiB. Potentially blocking bodies and Expect/Continue retain their required flush.

func (*HTTP1Settings) Set ΒΆ

func (h *HTTP1Settings) Set() *Builder

Set returns to the client builder.

func (*HTTP1Settings) WriteBufferSize ΒΆ

func (h *HTTP1Settings) WriteBufferSize(size int) *HTTP1Settings

WriteBufferSize selects the outgoing HTTP/1 buffer size, zero through 1 MiB. Zero restores the native default.

type HTTP2ConnectionCloseInfo ΒΆ

type HTTP2ConnectionCloseInfo = http2.ConnectionCloseInfo

HTTP2ConnectionCloseInfo describes a terminal HTTP/2 connection close.

type HTTP2ConnectionCloseOptions ΒΆ

type HTTP2ConnectionCloseOptions = http2.ConnectionCloseOptions

HTTP2ConnectionCloseOptions selects the optional final GOAWAY frame.

type HTTP2ReceiveWindowUpdateInfo ΒΆ

type HTTP2ReceiveWindowUpdateInfo = http2.ReceiveWindowUpdateInfo

type HTTP2RequestBodyInfo ΒΆ

type HTTP2RequestBodyInfo = http2.RequestBodyInfo

HTTP2RequestBodyInfo describes effective request fields and content length.

type HTTP2RequestBodyOptions ΒΆ

type HTTP2RequestBodyOptions = http2.RequestBodyOptions

HTTP2RequestBodyOptions controls upload reads and DATA framing.

type HTTP2Settings ΒΆ

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

HTTP2Settings represents HTTP/2 settings. https://lwthiker.com/networks/2022/06/17/http2-fingerprinting.html

func (*HTTP2Settings) ChainStreamDependencies ΒΆ

func (h *HTTP2Settings) ChainStreamDependencies(enabled bool) *HTTP2Settings

ChainStreamDependencies selects the newest still-open earlier stream with equal or greater weight as the dependency. Exclusive remains caller-controlled.

func (*HTTP2Settings) ConnectionClosePolicy ΒΆ

func (h *HTTP2Settings) ConnectionClosePolicy(
	policy func(HTTP2ConnectionCloseInfo) HTTP2ConnectionCloseOptions,
) *HTTP2Settings

ConnectionClosePolicy selects a final GOAWAY on terminal HTTP/2 close. Nil retains native behavior. The callback runs once outside connection locks and must return promptly, be concurrency safe and not reenter the connection.

func (*HTTP2Settings) ConnectionFlow ΒΆ

func (h *HTTP2Settings) ConnectionFlow(size uint32) *HTTP2Settings

ConnectionFlow sets the flow control for the HTTP/2 connection.

func (*HTTP2Settings) EnablePush ΒΆ

func (h *HTTP2Settings) EnablePush(size uint32) *HTTP2Settings

EnablePush enables HTTP/2 server push functionality.

func (*HTTP2Settings) HTTP1RequiredCache ΒΆ

func (h *HTTP2Settings) HTTP1RequiredCache(capacity int) *HTTP2Settings

HTTP1RequiredCache bounds remembered HTTPS origins requiring HTTP/1 in the JA TCP transport. Zero disables remembering and keeps per-request fallback. Chrome profiles select 100; Firefox and generic TLS profiles keep it disabled. Entries are client-local LRU state shared by proxy routes, without a TTL or disk persistence. HTTP/3 remains eligible. The valid range is 0..1048576.

func (*HTTP2Settings) HeaderPriority ΒΆ

func (h *HTTP2Settings) HeaderPriority(policy func(http2.PriorityRequest) http2.PriorityParam) *HTTP2Settings

HeaderPriority selects HTTP/2 HEADERS priority per request. The request is a read-only view. The callback must be safe for concurrent connections and must not reenter the client. Nil restores PriorityParam.

func (*HTTP2Settings) HeaderTableSize ΒΆ

func (h *HTTP2Settings) HeaderTableSize(size uint32) *HTTP2Settings

HeaderTableSize sets the header table size for HTTP/2 settings.

func (*HTTP2Settings) HealthCheckPayload ΒΆ

func (h *HTTP2Settings) HealthCheckPayload(payload *[8]byte) *HTTP2Settings

HealthCheckPayload selects automatic idle-PING data. Nil restores random payloads. The value is copied; explicit Ping and peer-PING echoes are unchanged.

func (*HTTP2Settings) HpackDeduplicateTableSizeUpdates ΒΆ

func (h *HTTP2Settings) HpackDeduplicateTableSizeUpdates(enabled bool) *HTTP2Settings

HpackDeduplicateTableSizeUpdates suppresses updates for repeated peer table capacities while retaining pending shrink/grow instructions.

func (*HTTP2Settings) HpackDefaultRepresentation ΒΆ

func (h *HTTP2Settings) HpackDefaultRepresentation(rep HPACKRepresentation) *HTTP2Settings

HpackDefaultRepresentation sets the fallback for fields without an override. HPACKDefault retains upstream indexing, table eviction and Huffman behavior.

func (*HTTP2Settings) HpackHuffman ΒΆ

func (h *HTTP2Settings) HpackHuffman(mode HPACKHuffmanMode) *HTTP2Settings

HpackHuffman chooses automatic, always or disabled Huffman string encoding.

func (*HTTP2Settings) HpackIndexingLimit ΒΆ

func (h *HTTP2Settings) HpackIndexingLimit(limit func(tableCapacity uint32) uint32) *HTTP2Settings

HpackIndexingLimit bounds new dynamic entries by their HPACK size (including 32 bytes of overhead), as a function of the current encoder table capacity. Existing exact entries remain reusable. Nil restores the upstream limit.

func (*HTTP2Settings) HpackNameReferencePolicy ΒΆ

func (h *HTTP2Settings) HpackNameReferencePolicy(policy HPACKNameReferencePolicy) *HTTP2Settings

HpackNameReferencePolicy controls which matching field name a literal refers to.

func (*HTTP2Settings) HpackPolicy ΒΆ

func (h *HTTP2Settings) HpackPolicy(policy func(name, value string) HPACKRepresentation) *HTTP2Settings

HpackPolicy selects representations by field name and value. Per-name HpackRepresentation overrides take precedence. The callback must be safe for concurrent connections and must not reenter the client.

func (*HTTP2Settings) HpackRepresentation ΒΆ

func (h *HTTP2Settings) HpackRepresentation(name string, rep HPACKRepresentation) *HTTP2Settings

HpackRepresentation overrides the policy for one field, including pseudo-fields.

func (*HTTP2Settings) InitialPeerSettings ΒΆ

func (h *HTTP2Settings) InitialPeerSettings(
	policy func([]http2.Setting) ([]http2.Setting, error),
) *HTTP2Settings

InitialPeerSettings selects which authenticated ALPS settings initialize an HTTP/2 connection. It receives a private slice before the first HTTP bytes, must return promptly and be safe across connections. Errors abort the unsent connection. Nil uses the native engine's settings semantics. Ordinary wire SETTINGS remain owned by the HTTP engine. Set this after Impersonate to override the selected profile's initial-settings policy.

func (*HTTP2Settings) InitialStreamID ΒΆ

func (h *HTTP2Settings) InitialStreamID(id uint32) *HTTP2Settings

InitialStreamID sets the initial stream id for HTTP/2 streams.

func (*HTTP2Settings) InitialWindowSize ΒΆ

func (h *HTTP2Settings) InitialWindowSize(size uint32) *HTTP2Settings

InitialWindowSize sets the initial window size for HTTP/2 streams.

func (*HTTP2Settings) MaxConcurrentStreams ΒΆ

func (h *HTTP2Settings) MaxConcurrentStreams(size uint32) *HTTP2Settings

MaxConcurrentStreams sets the maximum number of concurrent streams in HTTP/2.

func (*HTTP2Settings) MaxEncoderHeaderTableSize ΒΆ

func (h *HTTP2Settings) MaxEncoderHeaderTableSize(size uint32) *HTTP2Settings

MaxEncoderHeaderTableSize bounds the request encoder's table, independently of HeaderTableSize (our advertised decoder capacity). Zero retains upstream defaults. The native engine supports limits up to math.MaxInt32.

func (*HTTP2Settings) MaxFrameSize ΒΆ

func (h *HTTP2Settings) MaxFrameSize(size uint32) *HTTP2Settings

MaxFrameSize sets the maximum frame size for HTTP/2 frames.

func (*HTTP2Settings) MaxHeaderListSize ΒΆ

func (h *HTTP2Settings) MaxHeaderListSize(size uint32) *HTTP2Settings

MaxHeaderListSize sets the maximum size of the header list in HTTP/2.

func (*HTTP2Settings) NoRFC7540Priorities ΒΆ

func (h *HTTP2Settings) NoRFC7540Priorities(size uint32) *HTTP2Settings

NoRFC7540Priorities disables RFC 7540 priority signaling in HTTP/2.

func (*HTTP2Settings) PingTimeout ΒΆ

func (h *HTTP2Settings) PingTimeout(timeout time.Duration) *HTTP2Settings

PingTimeout bounds an automatic HTTP/2 health PING's acknowledgement wait. Zero retains the HTTP engine default. Negative durations are invalid.

func (*HTTP2Settings) PriorityFrames ΒΆ

func (h *HTTP2Settings) PriorityFrames(priorityFrames []http2.PriorityFrame) *HTTP2Settings

PriorityFrames sets the priority frames for HTTP/2.

func (*HTTP2Settings) PriorityParam ΒΆ

func (h *HTTP2Settings) PriorityParam(priorityParam http2.PriorityParam) *HTTP2Settings

PriorityParam sets a fixed HTTP/2 HEADERS priority and replaces HeaderPriority. Stream dependency chaining remains independently controlled by ChainStreamDependencies.

func (*HTTP2Settings) ReadIdleTimeout ΒΆ

func (h *HTTP2Settings) ReadIdleTimeout(timeout time.Duration) *HTTP2Settings

ReadIdleTimeout schedules an HTTP/2 health PING after this period without peer frames. Zero disables periodic probes. Browser profiles override the generic transport default; it is independent of TCP socket keepalive.

func (*HTTP2Settings) ReceiveWindowUpdatePolicy ΒΆ

func (h *HTTP2Settings) ReceiveWindowUpdatePolicy(policy func(HTTP2ReceiveWindowUpdateInfo) bool) *HTTP2Settings

ReceiveWindowUpdatePolicy controls batching of returned HTTP/2 receive credit. Nil restores native behavior. The callback runs under the connection lock; it must return promptly, be concurrency safe and never reenter the transport. An installed policy owns batching even when the peer's advertised credit is exhausted. It must eventually return consumed credit to permit more data.

func (*HTTP2Settings) RequestBodyPolicy ΒΆ

func (h *HTTP2Settings) RequestBodyPolicy(
	policy func(HTTP2RequestBodyInfo) HTTP2RequestBodyOptions,
) *HTTP2Settings

RequestBodyPolicy selects upload source-read boundaries and DATA limits from effective wire fields, without consuming the body. Nil uses native behavior. The callback must be concurrency safe and never reenter the transport.

func (*HTTP2Settings) Set ΒΆ

func (h *HTTP2Settings) Set() *Builder

Set applies the accumulated HTTP/2 settings. It configures the HTTP/2 settings for the surf client.

func (*HTTP2Settings) StreamReceiveWindow ΒΆ

func (h *HTTP2Settings) StreamReceiveWindow(size uint32) *HTTP2Settings

StreamReceiveWindow raises each client-created stream's credit after HEADERS. Zero uses InitialWindowSize; a nonzero window must be at least that size.

func (*HTTP2Settings) WriteBufferSize ΒΆ

func (h *HTTP2Settings) WriteBufferSize(size int) *HTTP2Settings

WriteBufferSize sets the HTTP/2 connection writer buffer. Zero retains the native default; the maximum is 1 MiB. Each DATA frame is still flushed.

type HTTP3GreaseFrame ΒΆ

type HTTP3GreaseFrame = http3.GreaseFrame

HTTP3GreaseFrame describes one RFC 9114 reserved frame and its payload.

type HTTP3PriorityUpdater ΒΆ

type HTTP3PriorityUpdater = http3.PriorityUpdater

HTTP3PriorityUpdater queues RFC 9218 priority changes for one open request. Update is concurrency safe; it does not change local QUIC upload scheduling.

type HTTP3RequestBodyReadInfo ΒΆ

type HTTP3RequestBodyReadInfo = http3.RequestBodyReadInfo

HTTP3RequestBodyReadInfo contains validated wire fields and the effective buffer size.

type HTTP3Settings ΒΆ

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

HTTP3Settings configures HTTP/3 SETTINGS, response limits and request options. Use Builder.QUICSettings for the underlying QUIC transport and handshake.

func (*HTTP3Settings) AdditionalSettings ΒΆ

func (h *HTTP3Settings) AdditionalSettings(settings g.MapOrd[uint64, uint64]) *HTTP3Settings

AdditionalSettings merges ordered HTTP/3 SETTINGS. Existing keys keep their position; new keys append in input order. Advertising a setting does not add implementation support for extensions such as WebTransport. QPACK settings configure the receive-side decoder; request encoding is configured separately.

func (*HTTP3Settings) AltUsed ΒΆ

func (h *HTTP3Settings) AltUsed(enabled bool) *HTTP3Settings

AltUsed sends the current request's destination authority in the Alt-Used header on HTTP/3 attempts. The Firefox desktop profile enables this to match its captured alternative-service requests. Explicit headers take precedence. Port 443 is omitted; non-default ports and IPv6 brackets are preserved.

func (*HTTP3Settings) AlternativeServiceBackoff ΒΆ

func (h *HTTP3Settings) AlternativeServiceBackoff(policy AlternativeServiceBackoff) *HTTP3Settings

AlternativeServiceBackoff selects the retry delay after a failed alternative handshake. Cancellation and a TCP race win do not count as service failure. The callback must be prompt, concurrency safe, and must not reenter this client.

func (*HTTP3Settings) ClientHandshake ΒΆ

func (h *HTTP3Settings) ClientHandshake(config *quic.ClientHandshake) *HTTP3Settings

ClientHandshake sets optional QUIC handshake controls. The supplied values are snapshotted; nil removes this override and retains any QUICConfig controls. Use Builder.QUICSettings for fluent configuration of individual controls.

func (*HTTP3Settings) ClientHelloFactory ΒΆ

func (h *HTTP3Settings) ClientHelloFactory(factory func() (utls.ClientHelloSpec, error)) *HTTP3Settings

ClientHelloFactory supplies a fresh QUIC template per connection attempt, including retries after version negotiation. The factory may run concurrently. Returned templates must not share mutable extensions with other attempts.

func (*HTTP3Settings) ClientHelloSpec ΒΆ

func (h *HTTP3Settings) ClientHelloSpec(spec *utls.ClientHelloSpec) *HTTP3Settings

ClientHelloSpec sets an explicit QUIC ClientHello template. It must contain QUICTransportParametersExtension and ALPNExtension; TCP templates are rejected. QUIC supplies real transport parameters and the HTTP/3 ALPN for each dial. Browser TCP JA settings remain independent. Nil restores standard crypto/tls.

func (*HTTP3Settings) CoalesceInitialSettings ΒΆ

func (h *HTTP3Settings) CoalesceInitialSettings(enabled bool) *HTTP3Settings

CoalesceInitialSettings prepares SETTINGS before the first application flight when peer credit permits. With early keys, preparation precedes Initial packetization unless FlushEarlySettings is enabled. Backpressure keeps an asynchronous write on the same stream. Control-frame factories must not block.

func (*HTTP3Settings) CoalesceRequestHeaders ΒΆ

func (h *HTTP3Settings) CoalesceRequestHeaders(enabled bool) *HTTP3Settings

CoalesceRequestHeaders stages initial priority, ready QPACK encoder instructions, HEADERS and a bodyless request's FIN together. Busy or blocked critical streams retain their asynchronous writer without holding requests.

func (*HTTP3Settings) CompactPriorityUpdates ΒΆ

func (h *HTTP3Settings) CompactPriorityUpdates(enabled bool) *HTTP3Settings

CompactPriorityUpdates omits spaces after commas in PRIORITY_UPDATE fields. It applies to initial frames and later HTTP3PriorityUpdater.Update calls.

func (*HTTP3Settings) ConnectionCoalescing ΒΆ

func (h *HTTP3Settings) ConnectionCoalescing(enabled bool) *HTTP3Settings

ConnectionCoalescing permits verified HTTP/3 connections to serve additional authorities after certificate and route checks. Client/proxy ownership stays isolated. Insecure TLS, custom verification and configured client credentials keep dedicated connections. Chrome enables this; a plain client does not.

func (*HTTP3Settings) ConnectionIDGenerator ΒΆ

func (h *HTTP3Settings) ConnectionIDGenerator(generator quic.ConnectionIDGenerator) *HTTP3Settings

ConnectionIDGenerator supplies the official quic-go connection ID generator. It takes precedence over ConnectionIDLength and may generate zero-length IDs.

func (*HTTP3Settings) ConnectionIDLength ΒΆ

func (h *HTTP3Settings) ConnectionIDLength(length int) *HTTP3Settings

ConnectionIDLength sets the length of locally generated connection IDs. Valid explicit lengths are 0 through 20. Zero uses a zero-length generator and a dedicated UDP socket per connection. Unset retains quic-go's 4-byte default. This does not control the independently generated initial destination ID.

func (*HTTP3Settings) ConnectionPoolPartition ΒΆ

func (h *HTTP3Settings) ConnectionPoolPartition(partition func(context.Context, string) string) *HTTP3Settings

ConnectionPoolPartition adds an application isolation key to HTTP/3 pooling. Connections from different keys never share, even for the same authority. The callback must be concurrency safe and stable for an attempt. Nil uses the built client's network context; browser discovery partitions still apply.

func (*HTTP3Settings) ConnectionRacing ΒΆ

func (h *HTTP3Settings) ConnectionRacing(enabled bool) *HTTP3Settings

ConnectionRacing prepares HTTP/3 and a TCP backup concurrently. Requests wait for selection unless EarlyData enables an eligible bodyless GET/HEAD; then EarlyDataBackup controls whether TCP can still win before QUIC confirms. Disabled by default, independently of the selected profile's delay policy.

func (*HTTP3Settings) ConnectionRacingPolicy ΒΆ

func (h *HTTP3Settings) ConnectionRacingPolicy(policy ConnectionRacingPolicy) *HTTP3Settings

ConnectionRacingPolicy selects a delay from per-origin observations. Nil uses Surf's 100ms default. Enable separately with ConnectionRacing(true). This setter replaces any fixed delay previously selected with TCPFallbackDelay.

func (*HTTP3Settings) ControlGreaseFrames ΒΆ

func (h *HTTP3Settings) ControlGreaseFrames(frames ...HTTP3GreaseFrame) *HTTP3Settings

ControlGreaseFrames adds reserved frames after SETTINGS on every connection. Types must be 0x1f*N+0x21. Frames and payloads are copied.

func (*HTTP3Settings) ControlGreaseFramesFactory ΒΆ

func (h *HTTP3Settings) ControlGreaseFramesFactory(factory func() ([]HTTP3GreaseFrame, error)) *HTTP3Settings

ControlGreaseFramesFactory generates fresh frames once per connection. The callback must be safe for concurrent connections.

func (*HTTP3Settings) Discovery ΒΆ

func (h *HTTP3Settings) Discovery(enabled bool) *HTTP3Settings

Discovery learns HTTP/3 alternatives from authenticated Alt-Svc responses and HTTPS DNS records. Without an advertisement requests use TCP. ForceHTTP3 retains its direct-attempt behavior. Cache and failures belong to this client.

func (*HTTP3Settings) ECHClientHelloInner ΒΆ

func (h *HTTP3Settings) ECHClientHelloInner(policy utls.ECHClientHelloInnerFunc) *HTTP3Settings

ECHClientHelloInner supplies the real QUIC ECH inner ClientHello policy. Browser profiles select their policy automatically. Nil restores engine defaults.

func (*HTTP3Settings) EarlyData ΒΆ

func (h *HTTP3Settings) EarlyData(enabled bool) *HTTP3Settings

EarlyData opts bodyless GET and HEAD requests into TLS 0-RTT on resumed HTTP/3 connections. Disabled by default. Enable only when replay of these requests is acceptable; POST and requests with bodies always wait for 1-RTT. A TLS ClientSessionCache is needed to resume a connection. Standard TLS and custom browser ClientHello templates support this, including accepted ECH. Peer SETTINGS are retained with each exact ticket. A ticket without this application state still supports ordinary TLS resumption, without early data.

func (*HTTP3Settings) EarlyDataBackup ΒΆ

func (h *HTTP3Settings) EarlyDataBackup(enabled bool) *HTTP3Settings

EarlyDataBackup keeps TCP preparation active until the QUIC handshake finishes, while eligible requests can already use 0-RTT. A ready TCP backup cancels the early attempt and sends the bodyless GET/HEAD over TCP. The Firefox profile enables this policy. False selects a QUIC connection as soon as early keys are ready, following Chrome. Enable early data separately with EarlyData.

func (*HTTP3Settings) EarlyDataRestart ΒΆ

func (h *HTTP3Settings) EarlyDataRestart(enabled bool) *HTTP3Settings

EarlyDataRestart recreates HTTP/3 state on the same QUIC connection when TLS rejects 0-RTT. Requests restart once after verified TLS; rejected SETTINGS and QPACK state are discarded. It does not enable early data or replay unsafe request bodies. Firefox desktop enables this policy automatically.

func (*HTTP3Settings) EarlyRequestPolicy ΒΆ

func (h *HTTP3Settings) EarlyRequestPolicy(policy EarlyRequestPolicy) *HTTP3Settings

EarlyRequestPolicy controls whether an eligible bodyless GET/HEAD may be sent before TLS authentication. EarlyData must also be enabled. False waits for the handshake while preserving the TLS early-data offer and protocol setup. Chrome requires prior confirmed QUIC support in this client's transport; nil retains the normal EarlyData eligibility. The policy is snapshotted at Build, must return promptly and must be safe for concurrent calls.

func (*HTTP3Settings) EnableConnectProtocol ΒΆ

func (h *HTTP3Settings) EnableConnectProtocol(num uint64) *HTTP3Settings

EnableConnectProtocol enables the extended CONNECT protocol (RFC 9220).

func (*HTTP3Settings) EnableDatagrams ΒΆ

func (h *HTTP3Settings) EnableDatagrams(enabled bool) *HTTP3Settings

EnableDatagrams configures both QUIC and HTTP/3 datagram support.

func (*HTTP3Settings) EnableWebtransport ΒΆ

func (h *HTTP3Settings) EnableWebtransport(num uint64) *HTTP3Settings

EnableWebtransport advertises a WebTransport setting. It does not implement a WebTransport application protocol.

func (*HTTP3Settings) ExpireFailedAlternatives ΒΆ

func (h *HTTP3Settings) ExpireFailedAlternatives(enabled bool) *HTTP3Settings

ExpireFailedAlternatives discards a failed advertisement when its retry interval expires; a new advertisement or DNS answer is then required.

func (*HTTP3Settings) FlushEarlySettings ΒΆ

func (h *HTTP3Settings) FlushEarlySettings(enabled bool) *HTTP3Settings

FlushEarlySettings gives initial SETTINGS a send opportunity before requests use a resumed early connection. Sendable Initial CRYPTO is packetized first; pacing, congestion and flow control retain authority over packet boundaries. This does not enable early data. Chrome enables it; Firefox keeps its own initialization order. Control-frame factories must not block.

func (*HTTP3Settings) Grease ΒΆ

func (h *HTTP3Settings) Grease() *HTTP3Settings

Grease generates a fresh reserved SETTINGS identifier/value per connection. Call GreaseFactory(nil) to disable generated SETTINGS GREASE.

func (*HTTP3Settings) GreaseFactory ΒΆ

func (h *HTTP3Settings) GreaseFactory(factory func() (uint64, uint64, error)) *HTTP3Settings

GreaseFactory generates one reserved SETTINGS pair for each new HTTP/3 connection. It must be concurrency safe, return promptly and not reenter the transport. Nil disables it. Errors are returned before control-stream writes.

func (*HTTP3Settings) H3Datagram ΒΆ

func (h *HTTP3Settings) H3Datagram(num uint64) *HTTP3Settings

H3Datagram sets a custom H3_DATAGRAM value for datagram support.

func (*HTTP3Settings) HTTPSRecordsLookup ΒΆ

func (h *HTTP3Settings) HTTPSRecordsLookup(lookup HTTPSRecordsLookup) *HTTP3Settings

HTTPSRecordsLookup supplies HTTPS records from an application resolver. Nil uses the client's configured DNS transport and system resolver addresses. No public DNS provider is substituted. Proxies bypass local HTTPS discovery.

func (*HTTP3Settings) HTTPSRecordsWait ΒΆ

func (h *HTTP3Settings) HTTPSRecordsWait(policy func(time.Duration) time.Duration) *HTTP3Settings

HTTPSRecordsWait chooses the extra wait for an optional built-in HTTPS DNS query after address queries finish. Zero means no supplemental deadline. Explicit HTTPSRecordsLookup callbacks retain their own deadlines.

func (*HTTP3Settings) IgnoreIPMatching ΒΆ

func (h *HTTP3Settings) IgnoreIPMatching(enabled bool) *HTTP3Settings

IgnoreIPMatching permits a server's NOIP connection option to waive the IP check for otherwise eligible coalescing. It requires ConnectionCoalescing. Chromium 158's source default is false; advertising NOIP alone does not enable it.

func (*HTTP3Settings) MaxDataFrameSize ΒΆ

func (h *HTTP3Settings) MaxDataFrameSize(size int) *HTTP3Settings

MaxDataFrameSize caps request DATA payloads. Zero preserves one frame per body read or Write. This does not set QUIC packet boundaries.

func (*HTTP3Settings) MaxFieldSectionSize ΒΆ

func (h *HTTP3Settings) MaxFieldSectionSize(num uint64) *HTTP3Settings

MaxFieldSectionSize sets the maximum size of a field section the peer is willing to accept.

func (*HTTP3Settings) MaxResponseHeaderBytes ΒΆ

func (h *HTTP3Settings) MaxResponseHeaderBytes(limit int) *HTTP3Settings

MaxResponseHeaderBytes sets the local response header limit. Zero restores Surf's default. Use MaxFieldSectionSize separately for the advertised setting.

func (*HTTP3Settings) OnOrigin ΒΆ

func (h *HTTP3Settings) OnOrigin(callback func(*quic.Conn, []string)) *HTTP3Settings

OnOrigin observes newly learned canonical origins after a complete server ORIGIN frame. Each supplied slice belongs to the callback. It must not block or reenter the connection and may run concurrently for different connections. OriginFrames and ConnectionCoalescing must be enabled to learn origins.

func (*HTTP3Settings) OnResponseHeaders ΒΆ

func (h *HTTP3Settings) OnResponseHeaders(callback func(*http.Request, *http.Response) error) *HTTP3Settings

OnResponseHeaders observes every valid HTTP/3 response header block, including 1xx, before tracing or delivery. Returning an error aborts the request. The callback must return promptly, must not mutate either argument or read the body, and must be safe for concurrent requests. Nil removes the callback.

func (*HTTP3Settings) OriginFrameLimit ΒΆ

func (h *HTTP3Settings) OriginFrameLimit(limit int) *HTTP3Settings

OriginFrameLimit bounds distinct learned origins per connection. Zero uses 20; valid explicit limits are 1 through 65536. Invalid entries and duplicates do not consume capacity. Lowering this on a builder does not affect built clients.

func (*HTTP3Settings) OriginFrames ΒΆ

func (h *HTTP3Settings) OriginFrames(enabled bool) *HTTP3Settings

OriginFrames accepts server ORIGIN frames for connection coalescing, permitting matching destinations to skip DNS. Certificate checks still apply. It requires ConnectionCoalescing. Chrome enables it; unknown frames otherwise remain ignored.

func (*HTTP3Settings) PriorityUpdates ΒΆ

func (h *HTTP3Settings) PriorityUpdates(enabled bool) *HTTP3Settings

PriorityUpdates sends RFC 9218 control frames for explicit, nondefault request Priority headers. Independent of GREASE and local StreamPriority.

func (*HTTP3Settings) QUICConfig ΒΆ

func (h *HTTP3Settings) QUICConfig(config *quic.Config) *HTTP3Settings

QUICConfig replaces Surf's QUIC defaults with a snapshot of config. Zero-valued fields use the official quic-go defaults. Nil restores Surf's defaults. Token stores, tracers and callbacks retain their shared identity. RequireStreamCreditRelease is an advanced option for applications that manage incoming stream credit; it does not add a transport parameter to the handshake. Use Builder.QUICSettings for fluent configuration of individual options.

func (*HTTP3Settings) QpackBlockedStreams ΒΆ

func (h *HTTP3Settings) QpackBlockedStreams(num uint64) *HTTP3Settings

QpackBlockedStreams sets the maximum number of streams that can be blocked on QPACK.

func (*HTTP3Settings) QpackDrainingFraction ΒΆ

func (h *HTTP3Settings) QpackDrainingFraction(fraction float64) *HTTP3Settings

QpackDrainingFraction reserves a fraction [0,1] of the table for eviction. Old exact entries may be duplicated instead of acquiring new references.

func (*HTTP3Settings) QpackDynamicTable ΒΆ

func (h *HTTP3Settings) QpackDynamicTable(enabled bool) *HTTP3Settings

QpackDynamicTable enables request compression using the peer's dynamic table. QpackEncoderTableCapacity sets the local budget; peer SETTINGS cap that budget and the number of streams that may reference unacknowledged insertions.

func (*HTTP3Settings) QpackEagerStreamTypes ΒΆ

func (h *HTTP3Settings) QpackEagerStreamTypes(eager bool) *HTTP3Settings

QpackEagerStreamTypes queues stream type bytes at initialization for streams listed in QpackStreamOrder. False sends each type with its first instruction.

func (*HTTP3Settings) QpackEncoderCapacityRequiresSetting ΒΆ

func (h *HTTP3Settings) QpackEncoderCapacityRequiresSetting(enabled bool) *HTTP3Settings

QpackEncoderCapacityRequiresSetting keeps an omitted peer capacity distinct from an explicit zero. Zero announcements still use QpackEncoderZeroCapacity.

func (*HTTP3Settings) QpackEncoderCapacityTiming ΒΆ

func (h *HTTP3Settings) QpackEncoderCapacityTiming(timing QPACKCapacityTiming) *HTTP3Settings

QpackEncoderCapacityTiming queues capacity after peer SETTINGS or when encoding the next outgoing HEADERS block. It does not wait for server SETTINGS or force network delivery order between independent QUIC streams.

func (*HTTP3Settings) QpackEncoderTableCapacity ΒΆ

func (h *HTTP3Settings) QpackEncoderTableCapacity(capacity uint64) *HTTP3Settings

QpackEncoderTableCapacity limits the capacity announced for request encoding. The announcement is capped by peer SETTINGS. Dynamic request compression also requires QpackDynamicTable(true). QpackMaxTableCapacity separately configures the receive-side dynamic table advertised in our own SETTINGS.

func (*HTTP3Settings) QpackEncoderZeroCapacity ΒΆ

func (h *HTTP3Settings) QpackEncoderZeroCapacity(enabled bool) *HTTP3Settings

QpackEncoderZeroCapacity sends an explicit zero capacity instruction when the peer offers no dynamic table, initializing an otherwise lazy encoder stream.

func (*HTTP3Settings) QpackHuffman ΒΆ

func (h *HTTP3Settings) QpackHuffman(mode QPACKHuffmanMode) *HTTP3Settings

QpackHuffman selects native/always, strictly shorter, or raw string encoding.

func (*HTTP3Settings) QpackIndexing ΒΆ

func (h *HTTP3Settings) QpackIndexing(mode QPACKIndexingMode) *HTTP3Settings

QpackIndexing selects insertion of all eligible fields, only new names, or no new entries. Existing dynamic entries remain usable unless never indexed.

func (*HTTP3Settings) QpackIndexingPolicy ΒΆ

func (h *HTTP3Settings) QpackIndexingPolicy(policy func(name, value string) bool) *HTTP3Settings

QpackIndexingPolicy optionally filters new insertions by lowercase name/value. The callback may run concurrently on different connections and must not reenter the transport. Nil removes the filter. Never-index fields are always excluded.

func (*HTTP3Settings) QpackLiteralInsertNames ΒΆ

func (h *HTTP3Settings) QpackLiteralInsertNames(enabled bool) *HTTP3Settings

QpackLiteralInsertNames sends names literally in Insert instructions instead of referencing existing static/dynamic names.

func (*HTTP3Settings) QpackMaxTableCapacity ΒΆ

func (h *HTTP3Settings) QpackMaxTableCapacity(num uint64) *HTTP3Settings

QpackMaxTableCapacity sets the advertised and enforced receive-side QPACK dynamic table capacity. Zero selects the static-only decoder.

func (*HTTP3Settings) QpackMaxTrackedSections ΒΆ

func (h *HTTP3Settings) QpackMaxTrackedSections(limit uint64) *HTTP3Settings

QpackMaxTrackedSections bounds outstanding dynamic header/trailer sections. At the bound new sections use static encoding. Zero selects the default 4096.

func (*HTTP3Settings) QpackNeverIndex ΒΆ

func (h *HTTP3Settings) QpackNeverIndex(names ...string) *HTTP3Settings

QpackNeverIndex selects fields to encode as literals with QPACK's N bit. Names are copied and normalized. An empty list restores upstream encoding.

func (*HTTP3Settings) QpackPostBaseReferences ΒΆ

func (h *HTTP3Settings) QpackPostBaseReferences(enabled bool) *HTTP3Settings

QpackPostBaseReferences fixes Base before a section's insertions, allowing post-base references. False selects Base equal to Required Insert Count.

func (*HTTP3Settings) QpackResumptionErrorCode ΒΆ

func (h *HTTP3Settings) QpackResumptionErrorCode(policy func(previous, current uint64) http3.ErrCode) *HTTP3Settings

QpackResumptionErrorCode selects the close code for an incompatible nonzero table capacity after accepted 0-RTT. Browser profiles configure their source policy. Nil or a zero result keeps the RFC 9204 decoder-stream error. The callback may run concurrently on different connections and must not do I/O.

func (*HTTP3Settings) QpackSplitCookies ΒΆ

func (h *HTTP3Settings) QpackSplitCookies(enabled bool) *HTTP3Settings

QpackSplitCookies emits one cookie field per nonempty cookie-pair on HTTP/3. Field order and the caller's original headers are preserved.

func (*HTTP3Settings) QpackStopOnInsertionFailure ΒΆ

func (h *HTTP3Settings) QpackStopOnInsertionFailure(enabled bool) *HTTP3Settings

QpackStopOnInsertionFailure stops new insertion attempts for the rest of a section after the first entry cannot fit. Existing references remain usable.

func (*HTTP3Settings) QpackStreamOrder ΒΆ

func (h *HTTP3Settings) QpackStreamOrder(order ...QPACKStreamType) *HTTP3Settings

QpackStreamOrder reserves QPACK streams after the control stream in the given order, while peer credit permits. Omitted streams open on demand. Input is copied.

func (*HTTP3Settings) RequestBodyBufferSize ΒΆ

func (h *HTTP3Settings) RequestBodyBufferSize(size int) *HTTP3Settings

RequestBodyBufferSize sets reads from HTTP/3 request bodies (0 uses 8 KiB). It clears previously configured size and first-read policies. Sizes must be in [0, 16 MiB].

func (*HTTP3Settings) RequestBodyBufferSizePolicy ΒΆ

func (h *HTTP3Settings) RequestBodyBufferSizePolicy(policy func(int64) int) *HTTP3Settings

RequestBodyBufferSizePolicy chooses a buffer using ContentLength (-1 when unknown). It must be concurrency safe; zero uses 8 KiB. Nil restores the fixed size.

func (*HTTP3Settings) RequestBodyFirstReadSizePolicy ΒΆ

func (h *HTTP3Settings) RequestBodyFirstReadSizePolicy(policy func(HTTP3RequestBodyReadInfo) int) *HTTP3Settings

RequestBodyFirstReadSizePolicy caps the first nonempty HTTP/3 body read. Zero restores the normal buffer size; a positive result must not exceed it. The callback receives actual outgoing fields, including implicit headers, and runs before request bytes or QPACK state changes. It must be concurrency safe. Nil clears this policy. It does not change QUIC packet boundaries.

func (*HTTP3Settings) RequestGreaseFrames ΒΆ

func (h *HTTP3Settings) RequestGreaseFrames(frames ...HTTP3GreaseFrame) *HTTP3Settings

RequestGreaseFrames adds reserved frames before each request's HEADERS. Types must be 0x1f*N+0x21. Frames and payloads are copied.

func (*HTTP3Settings) RequestGreaseFramesFactory ΒΆ

func (h *HTTP3Settings) RequestGreaseFramesFactory(
	factory func(*http.Request) ([]HTTP3GreaseFrame, error),
) *HTTP3Settings

RequestGreaseFramesFactory generates frames for each request. The callback must be safe for concurrent connections and must not mutate the request.

func (*HTTP3Settings) Set ΒΆ

func (h *HTTP3Settings) Set() *Builder

Set applies the configured HTTP/3 settings to the client's transport.

func (*HTTP3Settings) SettingsH3Datagram ΒΆ

func (h *HTTP3Settings) SettingsH3Datagram(num uint64) *HTTP3Settings

SettingsH3Datagram sets the H3_DATAGRAM setting value.

func (*HTTP3Settings) StreamPriority ΒΆ

func (h *HTTP3Settings) StreamPriority(urgency int8, incremental bool) *HTTP3Settings

StreamPriority sets local QUIC scheduling for request data. Urgency is clipped to 0 through 7 by quic-go. This does not send a PRIORITY_UPDATE frame or set the HTTP Priority header. StreamSchedulingByCreation takes precedence when enabled; disable it through QUICSettings to select urgency-based scheduling.

func (*HTTP3Settings) TCPFallbackAfterQUICStart ΒΆ

func (h *HTTP3Settings) TCPFallbackAfterQUICStart(enabled bool) *HTTP3Settings

TCPFallbackAfterQUICStart starts the backup delay after DNS/socket preparation and initialization of the shared QUIC attempt. A reusable H2 session, or an existing TCP group for DNS-only H3 discovery, bypasses that initialization hold. A configured delay still applies. False starts the timer with request preparation. Chrome enables this policy. TCPFallbackDelay selects the original request-start timing; call this method afterward to combine a fixed delay with QUIC-start timing.

func (*HTTP3Settings) TCPFallbackDelay ΒΆ

func (h *HTTP3Settings) TCPFallbackDelay(delay time.Duration) *HTTP3Settings

TCPFallbackDelay replaces the profile's policy with a fixed nonnegative delay. Zero starts both handshakes immediately. Enable with ConnectionRacing(true).

type HTTPSRecord ΒΆ

type HTTPSRecord struct {
	Priority           uint16
	Target             string
	ALPN               []string
	Port               uint16
	IPv4Hint, IPv6Hint []netip.Addr
	TTL                time.Duration
	ECH                []byte
	Mandatory          []uint16
	NoDefaultALPN      bool
}

HTTPSRecord describes an RFC 9460 HTTPS service binding. Lookup callbacks must return resolved ServiceMode bindings with owned slices and honor cancellation. The built-in resolver follows CNAME/AliasMode chains.

type HTTPSRecordsLookup ΒΆ

type HTTPSRecordsLookup func(context.Context, string) ([]HTTPSRecord, error)

type Headers ΒΆ

type Headers http.Header

Headers represents a collection of HTTP Headers.

func (Headers) Clone ΒΆ

func (h Headers) Clone() Headers

Clone returns a copy of Headers or nil if Headers is nil.

func (Headers) Contains ΒΆ

func (h Headers) Contains(header g.String, patterns any) bool

Contains checks if the header contains any of the specified patterns. It accepts a header name and a pattern (or list of patterns) and returns a boolean value indicating whether any of the patterns are found in the header values. The patterns can be a string, a slice of strings, or a slice of *regexp.Regexp.

func (Headers) Del ΒΆ

func (h Headers) Del(key g.String)

Del deletes the values associated with a specified header key. It wraps the Del method from the textproto.MIMEHeader type.

func (Headers) Get ΒΆ

func (h Headers) Get(key g.String) g.String

Get returns the first value associated with a specified header key. It wraps the Get method from the textproto.MIMEHeader type.

func (Headers) Values ΒΆ

func (h Headers) Values(key g.String) g.Slice[g.String]

Values returns the values associated with a specified header key. It wraps the Values method from the textproto.MIMEHeader type.

type Impersonate ΒΆ

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

func (*Impersonate) Android ΒΆ

func (im *Impersonate) Android() *Impersonate

Android sets the OS to Android.

func (*Impersonate) Chrome ΒΆ

func (im *Impersonate) Chrome() *Builder

Chrome impersonates Chrome 158 on desktop/Android and its separate iOS profile.

func (*Impersonate) Firefox ΒΆ

func (im *Impersonate) Firefox() *Builder

Firefox impersonates Firefox 160 on desktop and the existing mobile profiles.

func (*Impersonate) IOS ΒΆ

func (im *Impersonate) IOS() *Impersonate

IOS sets the OS to iOS.

func (*Impersonate) Linux ΒΆ

func (im *Impersonate) Linux() *Impersonate

Linux sets the OS to Linux.

func (*Impersonate) MacOS ΒΆ

func (im *Impersonate) MacOS() *Impersonate

MacOS sets the OS to macOS.

func (*Impersonate) RandomOS ΒΆ

func (im *Impersonate) RandomOS() *Impersonate

RandomOS selects a random OS (Windows, macOS, Linux, Android, or iOS) for the impersonate.

func (*Impersonate) Windows ΒΆ

func (im *Impersonate) Windows() *Impersonate

Windows sets the OS to Windows.

type InitialCryptoLayoutInfo ΒΆ

type InitialCryptoLayoutInfo = quic.InitialCryptoLayoutInfo

InitialCryptoLayoutInfo supplies the ClientHello boundaries and live Initial packet budgets to an InitialCryptoLayout policy.

type JA ΒΆ

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

JA provides JA3/4 TLS fingerprinting capabilities for HTTP clients. JA is a method for creating SSL/TLS client fingerprints to identify and classify malware or other applications. This struct allows configuring various TLS ClientHello specifications to mimic different browsers and applications for advanced HTTP client behavior.

Reference: https://lwthiker.com/networks/2022/06/17/tls-fingerprinting.html

func (*JA) Android ΒΆ

func (j *JA) Android() *Builder

Android sets the JA3/4 fingerprint to mimic Android 11 OkHttp client.

func (*JA) Chrome ΒΆ

func (j *JA) Chrome() *Builder

Chrome applies the current Chrome 158 TLS template.

func (*JA) Chrome158 ΒΆ

func (j *JA) Chrome158() *Builder

Chrome158 applies the current Chrome TLS template with per-connection extension shuffling and the browser's ECH inner and session-cache policies.

func (*JA) CloseNotify ΒΆ

func (j *JA) CloseNotify(enabled bool) *JA

CloseNotify overrides sending a TLS close_notify alert on Close for JA-owned TCP connections. Chrome omits it; Firefox sends it. This does not change QUIC or explicit TLS half-closes. Chain before a terminal JA method.

func (*JA) DynamicRecordSizing ΒΆ

func (j *JA) DynamicRecordSizing(enabled bool) *JA

DynamicRecordSizing overrides adaptive TLS record sizing for JA-owned TCP connections. Browser defaults apply first. Chain before SetHelloSpec, SetHelloID or a terminal browser method such as Chrome or Firefox.

func (*JA) ECHClientHelloInner ΒΆ

func (j *JA) ECHClientHelloInner(policy utls.ECHClientHelloInnerFunc) *JA

ECHClientHelloInner supplies the real encrypted inner ClientHello policy. Chain before SetHelloSpec or SetHelloID. Nil restores the engine default.

func (*JA) Edge ΒΆ

func (j *JA) Edge() *Builder

Edge sets the JA3/4 fingerprint to mimic Microsoft Edge version 85.

func (*JA) Edge85 ΒΆ

func (j *JA) Edge85() *Builder

Edge85 sets the JA3/4 fingerprint to mimic Microsoft Edge version 85.

func (*JA) Edge106 ΒΆ

func (j *JA) Edge106() *Builder

Edge106 sets the JA3/4 fingerprint to mimic Microsoft Edge version 106.

func (*JA) Firefox ΒΆ

func (j *JA) Firefox() *Builder

Firefox sets the current Firefox desktop TLS fingerprint.

func (*JA) Firefox55 ΒΆ

func (j *JA) Firefox55() *Builder

Firefox55 sets the JA3/4 fingerprint to mimic Firefox version 55.

func (*JA) Firefox56 ΒΆ

func (j *JA) Firefox56() *Builder

Firefox56 sets the JA3/4 fingerprint to mimic Firefox version 56.

func (*JA) Firefox63 ΒΆ

func (j *JA) Firefox63() *Builder

Firefox63 sets the JA3/4 fingerprint to mimic Firefox version 63.

func (*JA) Firefox65 ΒΆ

func (j *JA) Firefox65() *Builder

Firefox65 sets the JA3/4 fingerprint to mimic Firefox version 65.

func (*JA) Firefox99 ΒΆ

func (j *JA) Firefox99() *Builder

Firefox99 sets the JA3/4 fingerprint to mimic Firefox version 99.

func (*JA) Firefox102 ΒΆ

func (j *JA) Firefox102() *Builder

Firefox102 sets the JA3/4 fingerprint to mimic Firefox version 102.

func (*JA) Firefox105 ΒΆ

func (j *JA) Firefox105() *Builder

Firefox105 sets the JA3/4 fingerprint to mimic Firefox version 105.

func (*JA) Firefox120 ΒΆ

func (j *JA) Firefox120() *Builder

Firefox120 sets the JA3/4 fingerprint to mimic Firefox version 120.

func (*JA) Firefox148 ΒΆ

func (j *JA) Firefox148() *Builder

Firefox148 sets the JA3/4 fingerprint to mimic Firefox version 148.

func (*JA) Firefox160 ΒΆ

func (j *JA) Firefox160() *Builder

Firefox160 sets the current Firefox 160 desktop TLS fingerprint.

func (*JA) IOS ΒΆ

func (j *JA) IOS() *Builder

IOS sets the JA3/4 fingerprint to mimic the latest iOS Safari browser (auto-detection).

func (*JA) IOS11 ΒΆ

func (j *JA) IOS11() *Builder

IOS11 sets the JA3/4 fingerprint to mimic iOS 11.1 Safari.

func (*JA) IOS12 ΒΆ

func (j *JA) IOS12() *Builder

IOS12 sets the JA3/4 fingerprint to mimic iOS 12.1 Safari.

func (*JA) IOS13 ΒΆ

func (j *JA) IOS13() *Builder

IOS13 sets the JA3/4 fingerprint to mimic iOS 13 Safari.

func (*JA) IOS14 ΒΆ

func (j *JA) IOS14() *Builder

IOS14 sets the JA3/4 fingerprint to mimic iOS 14 Safari.

func (*JA) KeepAlivePolicy ΒΆ

func (j *JA) KeepAlivePolicy(
	policy func(TCPKeepAliveInfo) TCPKeepAliveOptions,
) *JA

KeepAlivePolicy overrides browser TCP keepalive on Surf-owned dial functions. Chain before a terminal JA method. Nil preserves net.Dialer settings. Explicit custom DialContext and net.Dialer keepalive settings remain application-owned. The callback must return promptly, be concurrency safe and never reenter the client. Reusing HTTP/1 restarts its transition; closing cancels it. QUIC does not use TCP keepalive.

func (*JA) Randomized ΒΆ

func (j *JA) Randomized() *Builder

Randomized sets a completely randomized JA3/4 fingerprint.

func (*JA) RandomizedALPN ΒΆ

func (j *JA) RandomizedALPN() *Builder

RandomizedALPN sets a randomized JA3/4 fingerprint with ALPN (Application-Layer Protocol Negotiation).

func (*JA) RandomizedNoALPN ΒΆ

func (j *JA) RandomizedNoALPN() *Builder

RandomizedNoALPN sets a randomized JA3/4 fingerprint without ALPN.

func (*JA) Safari ΒΆ

func (j *JA) Safari() *Builder

Safari sets the JA3/4 fingerprint to mimic the latest Safari browser (auto-detection).

func (*JA) Safari26_3 ΒΆ

func (j *JA) Safari26_3() *Builder

Safari26_3 sets the TLS fingerprint to Safari 26.3 (also used by Chrome on iOS).

func (*JA) SetHelloID ΒΆ

func (j *JA) SetHelloID(id utls.ClientHelloID) *Builder

SetHelloID sets a ClientHelloID for the TLS connection.

The provided ClientHelloID is used to customize the TLS handshake. This should be a valid identifier that can be mapped to a specific ClientHelloSpec.

It returns a pointer to the Options struct for method chaining. This allows additional configuration methods to be called on the result.

Example usage:

JA().SetHelloID(utls.HelloChrome_Auto)

func (*JA) SetHelloSpec ΒΆ

func (j *JA) SetHelloSpec(spec utls.ClientHelloSpec) *Builder

SetHelloSpec sets a custom ClientHelloSpec for the TLS connection.

This method allows you to set a custom ClientHelloSpec to be used during the TLS handshake. The provided spec should be a valid ClientHelloSpec.

It returns a pointer to the Options struct for method chaining. This allows additional configuration methods to be called on the result.

Example usage:

JA().SetHelloSpec(spec)

func (*JA) ShuffleExtensions ΒΆ

func (j *JA) ShuffleExtensions() *JA

ShuffleExtensions enables Chromium's per-connection ClientHello extension shuffle: the extension order is randomized on every TLS handshake instead of staying fixed for the lifetime of the client. GREASE, padding and pre_shared_key keep their positions, as they are positionally invariant on the wire.

Chromium shuffles since v110, so a custom Chrome-derived spec needs this to stay consistent with the User-Agent it claims. Firefox keeps a fixed order β€” do not enable it there.

Unlike SetHelloID / SetHelloSpec this method is not terminal: it returns the JA struct, so it has to be chained before the spec is set.

Example usage:

JA().ShuffleExtensions().SetHelloSpec(spec)

type Multipart ΒΆ

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

Multipart represents multipart form data with fields and files.

func NewMultipart ΒΆ

func NewMultipart() *Multipart

NewMultipart creates a new empty Multipart object.

func (*Multipart) ContentType ΒΆ

func (m *Multipart) ContentType(ct g.String) *Multipart

ContentType sets the content type for the last added file. Must be called immediately after File/FileReader/FileString/FileBytes.

func (*Multipart) Field ΒΆ

func (m *Multipart) Field(name, value g.String) *Multipart

Field adds a form field to the multipart.

func (*Multipart) File ΒΆ

func (m *Multipart) File(fieldName g.String, file *fs.File) *Multipart

File adds a physical file to the multipart.

func (*Multipart) FileBytes ΒΆ

func (m *Multipart) FileBytes(fieldName, fileName g.String, data g.Bytes) *Multipart

FileBytes adds a file from byte slice to the multipart.

func (*Multipart) FileName ΒΆ

func (m *Multipart) FileName(name g.String) *Multipart

FileName overrides the filename for the last added file. Useful when you want a different name than the physical file.

func (*Multipart) FileReader ΒΆ

func (m *Multipart) FileReader(fieldName, fileName g.String, reader io.Reader) *Multipart

FileReader adds a file from io.Reader to the multipart.

func (*Multipart) FileString ΒΆ

func (m *Multipart) FileString(fieldName, fileName, content g.String) *Multipart

FileString adds a file from string content to the multipart.

func (*Multipart) Retry ΒΆ

func (m *Multipart) Retry() *Multipart

Retry controls whether the multipart body should be buffered in memory to support retries on status codes (429, 503, 5xx, etc.).

When set, the body is fully read into memory before sending, allowing the client to replay it on retry.

Recommended only for small requests (≀ 5–10 MB).

type MultipartFile ΒΆ

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

MultipartFile represents a single file for multipart upload.

type NetworkChangeAction ΒΆ

type NetworkChangeAction = profiles.NetworkChangeAction

NetworkChangeAction selects maintenance on existing connection pools.

type NetworkChangeInfo ΒΆ

type NetworkChangeInfo = profiles.NetworkChangeInfo

NetworkChangeInfo describes an address, link, route or local identity change.

type NetworkChangePolicy ΒΆ

type NetworkChangePolicy = profiles.NetworkChangePolicy

NetworkChangePolicy selects pool maintenance for a network notification.

type NetworkSettings ΒΆ

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

NetworkSettings configures native network notifications through the client builder. Browser defaults apply first; explicit overrides apply last.

func (*NetworkSettings) Automatic ΒΆ

func (n *NetworkSettings) Automatic(enabled bool) *NetworkSettings

Automatic enables native notifications. False leaves explicit NetworkChanged calls available, for applications that already own network notifications.

func (*NetworkSettings) CoalescingDelay ΒΆ

func (n *NetworkSettings) CoalescingDelay(delay time.Duration) *NetworkSettings

CoalescingDelay merges native notifications from the first event without extending the window. Valid values are zero through one minute.

func (*NetworkSettings) Identity ΒΆ

func (n *NetworkSettings) Identity(reader func([]netip.Addr) (string, error)) *NetworkSettings

Identity sets the native network identity reader. Nil disables it. A nil input requests a full refresh; other inputs identify neighbors acquiring a MAC. The first successful value is a baseline; later changes set IdentityChanged. Errors retain that baseline. The callback must return promptly, be safe across clients and not reenter the client. Identity values remain local.

func (*NetworkSettings) Policy ΒΆ

Policy selects maintenance for each event. Nil disables maintenance. The callback must return promptly, be concurrency safe and not reenter this client.

func (*NetworkSettings) Set ΒΆ

func (n *NetworkSettings) Set() *Builder

Set returns to the client builder.

type PacingAlgorithm ΒΆ

type PacingAlgorithm = quic.PacingAlgorithm

type PeerAckFrequency ΒΆ

type PeerAckFrequency = quic.PeerAckFrequency

type PeerAckFrequencyInfo ΒΆ

type PeerAckFrequencyInfo = quic.PeerAckFrequencyInfo

type PeerAckFrequencyPolicy ΒΆ

type PeerAckFrequencyPolicy = quic.PeerAckFrequencyPolicy

type PeerPacketInfo ΒΆ

type PeerPacketInfo = quic.PeerPacketInfo

PeerPacketInfo describes a routed packet whose keys are unavailable.

type PeerPacketRecovery ΒΆ

type PeerPacketRecovery = quic.PeerPacketRecovery

PeerPacketRecovery selects transport responses without accepting the packet.

type QPACKCapacityTiming ΒΆ

type QPACKCapacityTiming = http3.QPACKCapacityTiming

QPACKCapacityTiming controls when an outgoing capacity instruction is queued.

type QPACKHuffmanMode ΒΆ

type QPACKHuffmanMode = http3.QPACKHuffmanMode

type QPACKIndexingMode ΒΆ

type QPACKIndexingMode = http3.QPACKIndexingMode

type QPACKStreamType ΒΆ

type QPACKStreamType = http3.QPACKStreamType

QPACKStreamType identifies an HTTP/3 QPACK unidirectional stream.

type QUICSettings ΒΆ

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

QUICSettings configures the HTTP/3 transport through Surf's fluent API. Each setter changes only its own option, retaining the selected browser profile. Set returns the main Builder; ForceHTTP3 selects use of this transport.

func (*QUICSettings) AckDecimation ΒΆ

func (q *QUICSettings) AckDecimation(after, threshold uint64) *QUICSettings

AckDecimation selects a new packet threshold once the received packet number reaches the smallest received number plus after. It is not a received-packet count. A zero threshold disables decimation without negotiating ACK_FREQUENCY.

func (*QUICSettings) AckDelayRTTDivisor ΒΆ

func (q *QUICSettings) AckDelayRTTDivisor(divisor uint32) *QUICSettings

AckDelayRTTDivisor caps delayed ACKs by minRTT/divisor after decimation. Zero disables RTT scaling. MaxAckDelay still supplies the upper bound.

func (*QUICSettings) AckECN ΒΆ

func (q *QUICSettings) AckECN(mode AckECNMode) *QUICSettings

AckECN selects immediate ACKs for CE marks, CE transitions, or counting only.

func (*QUICSettings) AckFlushOnPacket ΒΆ

func (q *QUICSettings) AckFlushOnPacket(enabled bool) *QUICSettings

AckFlushOnPacket gives a queued ACK a send opportunity before the next received UDP datagram. Chrome enables this; Firefox retains receive batching. Socket backpressure can still delay the actual transmission.

func (*QUICSettings) AckMissingPacketLimit ΒΆ

func (q *QUICSettings) AckMissingPacketLimit(packets uint64) *QUICSettings

AckMissingPacketLimit bounds immediate ACKs following a gap in Window mode.

func (*QUICSettings) AckOnlyMaxDataThreshold ΒΆ

func (q *QUICSettings) AckOnlyMaxDataThreshold(threshold int) *QUICSettings

AckOnlyMaxDataThreshold solicits acknowledgment by repeating current MAX_DATA after a run of ACK-only packets. It grants no extra credit and replaces the periodic PING policy. Zero clears this policy; PTO probes remain independent.

func (*QUICSettings) AckOnlyPingThreshold ΒΆ

func (q *QUICSettings) AckOnlyPingThreshold(threshold int) *QUICSettings

AckOnlyPingThreshold controls extra PINGs after consecutive ACK-only packets. Zero retains native behavior; -1 disables these PINGs, preserving PTO probes.

func (*QUICSettings) AckPacketThreshold ΒΆ

func (q *QUICSettings) AckPacketThreshold(packets uint64) *QUICSettings

AckPacketThreshold sets the initial number of ack-eliciting packets per ACK. Zero uses the engine's native threshold. Only Application Data is affected.

func (*QUICSettings) AckProbePolicy ΒΆ

func (q *QUICSettings) AckProbePolicy(policy func(quic.AckProbeInfo) bool) *QUICSettings

AckProbePolicy replaces periodic ACK-only probes with a decision based on recovery state. It runs in the send loop and must not block or reenter the connection. Nil disables this callback. PTO recovery remains independent.

func (*QUICSettings) AckReordering ΒΆ

func (q *QUICSettings) AckReordering(mode AckReorderingMode) *QUICSettings

AckReordering selects how missing/out-of-order packets prompt ACKs.

func (*QUICSettings) ActiveConnectionIDLimit ΒΆ

func (q *QUICSettings) ActiveConnectionIDLimit(limit uint64) *QUICSettings

ActiveConnectionIDLimit sets the receive-side connection ID limit (at least 2). Zero selects quic-go's default.

func (*QUICSettings) AddressFallbackDelay ΒΆ

func (q *QUICSettings) AddressFallbackDelay(delay time.Duration) *QUICSettings

AddressFallbackDelay enables staggered QUIC attempts to resolved addresses. Zero preserves serial address attempts. Positive values require 1-RTT.

func (*QUICSettings) AllowConnectionWindowIncrease ΒΆ

func (q *QUICSettings) AllowConnectionWindowIncrease(allow func(*quic.Conn, uint64) bool) *QUICSettings

AllowConnectionWindowIncrease decides whether automatic receive window growth is permitted. The callback must not call connection or stream methods.

func (*QUICSettings) ApplicationProbePackets ΒΆ

func (q *QUICSettings) ApplicationProbePackets(count uint8) *QUICSettings

ApplicationProbePackets sets the 1-RTT PTO allowance (0..2). Zero preserves the native allowance. It does not change random number skipping.

func (*QUICSettings) ApplicationProbeSkipPacketNumber ΒΆ

func (q *QUICSettings) ApplicationProbeSkipPacketNumber(enabled bool) *QUICSettings

ApplicationProbeSkipPacketNumber controls the 1-RTT PTO gap independently of random PacketNumberSkipping. It overrides that setting for PTO only. Browser profiles select their explicit policy; native configs retain the legacy coupling.

func (*QUICSettings) CachedInitialRTT ΒΆ

func (q *QUICSettings) CachedInitialRTT(parameter uint64, minimum, maximum time.Duration) *QUICSettings

CachedInitialRTT learns measured RTT from this client's preceding direct connection to each origin. It owns parameter and encodes the measured RTT in microseconds; an empty history omits it. Local recovery uses the same estimate clamped to minimum..maximum. Proxy connections do not share this history. Parameter zero disables it. Bounds must be positive and ordered when enabled.

func (*QUICSettings) ClientHelloFactory ΒΆ

func (q *QUICSettings) ClientHelloFactory(factory func() (utls.ClientHelloSpec, error)) *QUICSettings

ClientHelloFactory supplies a fresh QUIC TLS template per connection attempt. It may run concurrently; templates must not share mutable extensions.

func (*QUICSettings) ClientHelloSpec ΒΆ

func (q *QUICSettings) ClientHelloSpec(spec *utls.ClientHelloSpec) *QUICSettings

ClientHelloSpec snapshots an explicit QUIC TLS template. Nil restores standard TLS.

func (*QUICSettings) CoalescePTOProbes ΒΆ

func (q *QUICSettings) CoalescePTOProbes(enabled bool) *QUICSettings

CoalescePTOProbes shares one datagram budget across eligible encryption spaces. It retains crypto PTO baselines and suppresses empty crypto follow-up probes; queued data can still be sent in every space. Firefox enables this policy.

func (*QUICSettings) CoalesceSmallEarlyPackets ΒΆ

func (q *QUICSettings) CoalesceSmallEarlyPackets(enabled bool) *QUICSettings

CoalesceSmallEarlyPackets lets 0-RTT use a datagram remainder below Go's ordinary coalescing threshold when a protected packet fits. Firefox enables this; other encryption spaces retain their usual threshold.

func (*QUICSettings) CompatibleVersionNegotiation ΒΆ

func (q *QUICSettings) CompatibleVersionNegotiation(enabled bool) *QUICSettings

CompatibleVersionNegotiation enables authenticated v1/v2 switching within a handshake (RFC 9368/9369). Versions lists the permitted versions; a custom transport-parameter layout can select their preference and GREASE ordering. Firefox enables this mechanism by default. Native clients keep it disabled.

func (*QUICSettings) CongestionControl ΒΆ

func (q *QUICSettings) CongestionControl(algorithm CongestionControlAlgorithm) *QUICSettings

CongestionControl selects Reno, RFC 9438 CUBIC, or fixed-point byte-mode CUBIC. Native restores the engine default. Pacing and loss detection are separate.

func (*QUICSettings) CongestionControlConnections ΒΆ

func (q *QUICSettings) CongestionControlConnections(count uint32) *QUICSettings

CongestionControlConnections sets the number of emulated byte-mode CUBIC connections (1..16). Zero means one; other algorithms allow only zero or one.

func (*QUICSettings) CongestionControlSegmentSize ΒΆ

func (q *QUICSettings) CongestionControlSegmentSize(bytes uint16) *QUICSettings

CongestionControlSegmentSize fixes the accounting segment independently of UDP packet size. Zero follows the path MTU; explicit values are 1200..65527.

func (*QUICSettings) ConnectionIDGenerator ΒΆ

func (q *QUICSettings) ConnectionIDGenerator(generator quic.ConnectionIDGenerator) *QUICSettings

ConnectionIDGenerator sets a custom generator, taking precedence over length.

func (*QUICSettings) ConnectionIDLength ΒΆ

func (q *QUICSettings) ConnectionIDLength(length int) *QUICSettings

ConnectionIDLength sets the local connection ID length, from 0 through 20. Zero uses a dedicated UDP socket for each connection.

func (*QUICSettings) DisableClientHelloScrambling ΒΆ

func (q *QUICSettings) DisableClientHelloScrambling(disabled bool) *QUICSettings

DisableClientHelloScrambling controls SNI/ECH CRYPTO fragmentation.

func (*QUICSettings) DisableConnectionIDRotation ΒΆ

func (q *QUICSettings) DisableConnectionIDRotation(disable bool) *QUICSettings

DisableConnectionIDRotation keeps the active ID on an unchanged path. Peer retirement and connection migration continue to replace IDs as needed.

func (*QUICSettings) DisablePathMTUDiscovery ΒΆ

func (q *QUICSettings) DisablePathMTUDiscovery(disabled bool) *QUICSettings

DisablePathMTUDiscovery controls whether QUIC probes for a larger path MTU.

func (*QUICSettings) DisableTransportParameterGrease ΒΆ

func (q *QUICSettings) DisableTransportParameterGrease(disabled bool) *QUICSettings

DisableTransportParameterGrease controls reserved transport parameters, including those supplied by a browser factory. False uses native QUIC GREASE.

func (*QUICSettings) ECHClientHelloInner ΒΆ

func (q *QUICSettings) ECHClientHelloInner(policy utls.ECHClientHelloInnerFunc) *QUICSettings

ECHClientHelloInner supplies the real QUIC ECH inner ClientHello policy.

func (*QUICSettings) EarlyDataResendOnPeerCrypto ΒΆ

func (q *QUICSettings) EarlyDataResendOnPeerCrypto(enabled bool) *QUICSettings

EarlyDataResendOnPeerCrypto repeats outstanding 0-RTT recovery tokens when authenticated Initial CRYPTO makes no TLS progress. The first Application ACK ends this mechanism. PING alone never repeats early STREAM data.

func (*QUICSettings) EnableDatagrams ΒΆ

func (q *QUICSettings) EnableDatagrams(enabled bool) *QUICSettings

EnableDatagrams configures both QUIC and HTTP/3 datagram support.

func (*QUICSettings) EnableStreamResetPartialDelivery ΒΆ

func (q *QUICSettings) EnableStreamResetPartialDelivery(enabled bool) *QUICSettings

EnableStreamResetPartialDelivery controls reliable stream resets.

func (*QUICSettings) FlushEarlyData ΒΆ

func (q *QUICSettings) FlushEarlyData(enabled bool) *QUICSettings

FlushEarlyData gives sendable Initial data and the early-ready callback's staged data separate send opportunities before releasing the connection. False permits coalescing with Initial; pacing and congestion still apply. HTTP/3's FlushEarlySettings enables this for its control-stream initialization.

func (*QUICSettings) HandshakeAckBeforeData ΒΆ

func (q *QUICSettings) HandshakeAckBeforeData(enabled bool) *QUICSettings

HandshakeAckBeforeData separates queued handshake ACKs from the first local Handshake CRYPTO flight without adding a timer or changing TLS verification.

func (*QUICSettings) HandshakeCryptoRecovery ΒΆ

func (q *QUICSettings) HandshakeCryptoRecovery(enabled bool) *QUICSettings

HandshakeCryptoRecovery tracks Handshake CRYPTO ranges and late original PTO ACKs. Disabling also removes its peer-probe retransmission policy.

func (*QUICSettings) HandshakeCryptoResendOnPeerProbe ΒΆ

func (q *QUICSettings) HandshakeCryptoResendOnPeerProbe(enabled bool) *QUICSettings

HandshakeCryptoResendOnPeerProbe resends unacknowledged Handshake CRYPTO on PING or non-progressing CRYPTO. Enabling also selects Handshake recovery.

func (*QUICSettings) HandshakeIdleTimeout ΒΆ

func (q *QUICSettings) HandshakeIdleTimeout(timeout time.Duration) *QUICSettings

HandshakeIdleTimeout sets the idle timeout during connection establishment. Zero selects quic-go's default.

func (*QUICSettings) HandshakeProbeOnlyWithData ΒΆ

func (q *QUICSettings) HandshakeProbeOnlyWithData(enabled bool) *QUICSettings

HandshakeProbeOnlyWithData suppresses empty follow-up Handshake probes. The first probe can still send PING; queued CRYPTO uses the full allowance.

func (*QUICSettings) HandshakeProbePackets ΒΆ

func (q *QUICSettings) HandshakeProbePackets(count uint8) *QUICSettings

HandshakeProbePackets sets the Handshake PTO allowance (0..2). Zero preserves the native allowance; the selected profile supplies its default.

func (*QUICSettings) HandshakeProbeSkipPacketNumber ΒΆ

func (q *QUICSettings) HandshakeProbeSkipPacketNumber(enabled bool) *QUICSettings

HandshakeProbeSkipPacketNumber controls a deliberate Handshake PTO number gap.

func (*QUICSettings) ImmediateACKOnPeerPing ΒΆ

func (q *QUICSettings) ImmediateACKOnPeerPing(enabled bool) *QUICSettings

ImmediateACKOnPeerPing selects immediate acknowledgment of a verified 1-RTT PING. Other application packets retain the configured ACK policy.

func (*QUICSettings) InitialACKResetsPTO ΒΆ

func (q *QUICSettings) InitialACKResetsPTO(enabled bool) *QUICSettings

InitialACKResetsPTO resets probe-timeout backoff on a new Initial ACK before peer address validation completes. Firefox selects this recovery policy.

func (*QUICSettings) InitialCongestionWindowPackets ΒΆ

func (q *QUICSettings) InitialCongestionWindowPackets(packets uint32) *QUICSettings

InitialCongestionWindowPackets sets the initial send window in datagram-sized packets (path MTU unless CongestionControlSegmentSize is fixed). Zero restores the engine default; supported explicit values are 2..10000.

func (*QUICSettings) InitialConnectionReceiveWindow ΒΆ

func (q *QUICSettings) InitialConnectionReceiveWindow(size uint64) *QUICSettings

InitialConnectionReceiveWindow sets the initial connection receive window.

func (*QUICSettings) InitialCryptoCoalescingBarrier ΒΆ

func (q *QUICSettings) InitialCryptoCoalescingBarrier(enabled bool) *QUICSettings

InitialCryptoCoalescingBarrier keeps later packet spaces out of an Initial datagram while Initial CRYPTO remains queued. It permits coalescing with the final Initial and does not wait for an ACK or handshake confirmation.

func (*QUICSettings) InitialCryptoFirstFrameSize ΒΆ

func (q *QUICSettings) InitialCryptoFirstFrameSize(min, max int) *QUICSettings

InitialCryptoFirstFrameSize selects a prefix size for cross-packet protection. A first packet carries that prefix and trailing ClientHello bytes, with the middle in following packets. Zero disables this layout. Bounds are 0..16384.

func (*QUICSettings) InitialCryptoFrameSplits ΒΆ

func (q *QUICSettings) InitialCryptoFrameSplits(min, max int) *QUICSettings

InitialCryptoFrameSplits sets an inclusive range of random split attempts per padded client Initial. Available padding bounds the actual number of splits.

func (*QUICSettings) InitialCryptoLayout ΒΆ

func (q *QUICSettings) InitialCryptoLayout(policy func(InitialCryptoLayoutInfo) [][]CryptoRange) *QUICSettings

InitialCryptoLayout chooses ordered ranges of the first ClientHello for each Initial packet from its SNI/ECH positions, unsent ranges and live packet budget. Each result must cover Remaining exactly once; invalid layouts fail before sending. The engine sends the first group and reconsiders the remaining bytes with the next packet's actual budget. Nil retains native preparation. The policy must support concurrent calls and return promptly. Later Initial data, including a HelloRetryRequest response, keeps normal stream ordering.

func (*QUICSettings) InitialCryptoProbePackets ΒΆ

func (q *QUICSettings) InitialCryptoProbePackets(count uint8) *QUICSettings

InitialCryptoProbePackets sets the Initial PTO allowance and preparation batch. Zero keeps the native allowance and a one-packet batch; valid counts are 0..2. A nonzero count enables byte-range recovery and original-packet ACK tracking.

func (*QUICSettings) InitialCryptoRecovery ΒΆ

func (q *QUICSettings) InitialCryptoRecovery(enabled bool) *QUICSettings

InitialCryptoRecovery tracks lost Initial bytes independently of their old frame boundaries and retires them when a packet copy is acknowledged. Browser profiles enable this automatically. Disabling clears its layout and probe batch.

func (*QUICSettings) InitialCryptoRecoveryLayout ΒΆ

func (q *QUICSettings) InitialCryptoRecoveryLayout(policy func(InitialCryptoLayoutInfo) [][]CryptoRange) *QUICSettings

InitialCryptoRecoveryLayout selects ordered lost ranges for each Initial packet's live budget. Offsets remain absolute across HelloRetryRequest; Length can include later Initial messages. A non-nil policy enables byte-range recovery. Nil restores sequential lost ranges while retaining the current recovery mode.

func (*QUICSettings) InitialCryptoResendOnPeerProbe ΒΆ

func (q *QUICSettings) InitialCryptoResendOnPeerProbe(enabled bool) *QUICSettings

InitialCryptoResendOnPeerProbe resends sent, unacknowledged Initial bytes on PING or CRYPTO input that delivers no new TLS bytes. Enabling also selects byte-range recovery. Browser profiles configure their own policy.

func (*QUICSettings) InitialDestinationConnectionIDLength ΒΆ

func (q *QUICSettings) InitialDestinationConnectionIDLength(length int) *QUICSettings

InitialDestinationConnectionIDLength sets the Initial destination ID length. Nonzero lengths must be 8 through 20; zero selects quic-go's default.

func (*QUICSettings) InitialDestinationConnectionIDLengthFactory ΒΆ

func (q *QUICSettings) InitialDestinationConnectionIDLengthFactory(factory func() (int, error)) *QUICSettings

InitialDestinationConnectionIDLengthFactory chooses a fresh 8..20 byte length per connection. Nil restores the fixed length. The factory may run concurrently.

func (*QUICSettings) InitialPTOMultiplier ΒΆ

func (q *QUICSettings) InitialPTOMultiplier(factor uint32) *QUICSettings

InitialPTOMultiplier controls probe timing before the first RTT measurement. Zero uses the native factor; supported explicit factors are 1..16.

func (*QUICSettings) InitialPacketNumber ΒΆ

func (q *QUICSettings) InitialPacketNumber(number uint64) *QUICSettings

InitialPacketNumber sets a fixed initial packet number and clears any factory.

func (*QUICSettings) InitialPacketNumberFactory ΒΆ

func (q *QUICSettings) InitialPacketNumberFactory(factory func() (uint64, error)) *QUICSettings

InitialPacketNumberFactory supplies a fresh initial number per connection. Nil restores the fixed number. The factory may run concurrently.

func (*QUICSettings) InitialPacketSize ΒΆ

func (q *QUICSettings) InitialPacketSize(size uint16) *QUICSettings

InitialPacketSize sets the initial packet size in bytes (at least 1200). Zero selects quic-go's default.

func (*QUICSettings) InitialPacketSizeFactory ΒΆ

func (q *QUICSettings) InitialPacketSizeFactory(factory func(net.Addr) (uint16, error)) *QUICSettings

InitialPacketSizeFactory selects the initial UDP payload size for the actual remote address. It must return promptly and be concurrency safe. Nil restores the fixed size. Results must fit the QUIC engine's supported packet sizes.

func (*QUICSettings) InitialPaddingMode ΒΆ

func (q *QUICSettings) InitialPaddingMode(mode quic.InitialPaddingMode) *QUICSettings

InitialPaddingMode selects encrypted PADDING or a zero-filled datagram tail after coalesced packets. Header-protection sample padding remains encrypted.

func (*QUICSettings) InitialPingFrames ΒΆ

func (q *QUICSettings) InitialPingFrames(min, max int) *QUICSettings

InitialPingFrames sets the inclusive random PING count in protected Initials. Both endpoints must be in 0..64. This does not affect 1-RTT ACK-only PINGs.

func (*QUICSettings) InitialProbeSkipPacketNumber ΒΆ

func (q *QUICSettings) InitialProbeSkipPacketNumber(enabled bool) *QUICSettings

InitialProbeSkipPacketNumber skips one Initial number when PTO fires to elicit an immediate ACK. This is independent of Application Data PacketNumberSkipping.

func (*QUICSettings) InitialRTT ΒΆ

func (q *QUICSettings) InitialRTT(estimate time.Duration) *QUICSettings

InitialRTT sets the local recovery estimate before the first measurement. Zero uses the native default. No transport parameter is advertised by it.

func (*QUICSettings) InitialStreamReceiveWindow ΒΆ

func (q *QUICSettings) InitialStreamReceiveWindow(size uint64) *QUICSettings

InitialStreamReceiveWindow sets the common initial stream receive window. It replaces any per-direction StreamReceiveWindows override.

func (*QUICSettings) KeepAlivePeriod ΒΆ

func (q *QUICSettings) KeepAlivePeriod(period time.Duration) *QUICSettings

KeepAlivePeriod sets the interval between keep-alive packets. Zero disables them.

func (*QUICSettings) LegacyAckFrequency ΒΆ

func (q *QUICSettings) LegacyAckFrequency(minimum time.Duration) *QUICSettings

LegacyAckFrequency enables the legacy single-byte ignore_order extension and advertises its minimum requested ACK delay. Zero disables it. The delay must be a whole number of microseconds no larger than MaxAckDelay. Local ACK policy remains in effect until a valid peer update arrives; this is receive support.

func (*QUICSettings) MaxAckDelay ΒΆ

func (q *QUICSettings) MaxAckDelay(delay time.Duration) *QUICSettings

MaxAckDelay sets the acknowledgment scheduling bound in whole milliseconds. Zero selects quic-go's default.

func (*QUICSettings) MaxCongestionWindowPackets ΒΆ

func (q *QUICSettings) MaxCongestionWindowPackets(packets int64) *QUICSettings

MaxCongestionWindowPackets caps the send window in accounting segments. Zero restores the engine default; -1 removes this packet-count ceiling.

func (*QUICSettings) MaxConnectionReceiveWindow ΒΆ

func (q *QUICSettings) MaxConnectionReceiveWindow(size uint64) *QUICSettings

MaxConnectionReceiveWindow sets the connection receive window limit.

func (*QUICSettings) MaxDatagramFrameSize ΒΆ

func (q *QUICSettings) MaxDatagramFrameSize(size uint64) *QUICSettings

MaxDatagramFrameSize sets the advertised QUIC datagram limit. Datagram support must also be enabled. Zero selects quic-go's default.

func (*QUICSettings) MaxIdleTimeout ΒΆ

func (q *QUICSettings) MaxIdleTimeout(timeout time.Duration) *QUICSettings

MaxIdleTimeout sets the maximum idle time after the handshake. Zero selects quic-go's default.

func (*QUICSettings) MaxIncomingStreams ΒΆ

func (q *QUICSettings) MaxIncomingStreams(limit int64) *QUICSettings

MaxIncomingStreams limits concurrent peer-initiated bidirectional streams. Zero selects quic-go's default; a negative value disallows them.

func (*QUICSettings) MaxIncomingUniStreams ΒΆ

func (q *QUICSettings) MaxIncomingUniStreams(limit int64) *QUICSettings

MaxIncomingUniStreams limits concurrent peer-initiated unidirectional streams. Zero selects quic-go's default; a negative value disallows them.

func (*QUICSettings) MaxStreamReceiveWindow ΒΆ

func (q *QUICSettings) MaxStreamReceiveWindow(size uint64) *QUICSettings

MaxStreamReceiveWindow sets the receive window limit for each stream.

func (*QUICSettings) MaxUDPPayloadSize ΒΆ

func (q *QUICSettings) MaxUDPPayloadSize(size uint64) *QUICSettings

MaxUDPPayloadSize sets the advertised UDP payload limit and actual receive size. It also enables advertising this parameter after OmitMaxUDPPayloadSize(true).

func (*QUICSettings) MinAckDelay ΒΆ

func (q *QUICSettings) MinAckDelay(delay time.Duration) *QUICSettings

MinAckDelay sets the floor for the RTT-scaled delay, within MaxAckDelay.

func (*QUICSettings) OmitInitialAckOnHandshake ΒΆ

func (q *QUICSettings) OmitInitialAckOnHandshake(omit bool) *QUICSettings

OmitInitialAckOnHandshake omits an ACK-only Initial when Handshake data is ready.

func (*QUICSettings) OmitLegacyResetStreamAt ΒΆ

func (q *QUICSettings) OmitLegacyResetStreamAt(omit bool) *QUICSettings

OmitLegacyResetStreamAt controls advertising the legacy reliable-reset parameter.

func (*QUICSettings) OmitMaxUDPPayloadSize ΒΆ

func (q *QUICSettings) OmitMaxUDPPayloadSize(omit bool) *QUICSettings

OmitMaxUDPPayloadSize omits the parameter and provisions the protocol default receive size when enabled. False advertises the current payload limit.

func (*QUICSettings) OnApplicationReady ΒΆ

func (q *QUICSettings) OnApplicationReady(callback func(*quic.Conn)) *QUICSettings

OnApplicationReady stages application data after verified TLS and peer parameters, before the next flight. It must not block or call CloseWithError; use OpenUniStream and TryWriteAll rather than blocking stream writes.

func (*QUICSettings) OnEarlyDataReady ΒΆ

func (q *QUICSettings) OnEarlyDataReady(callback func(*quic.Conn)) *QUICSettings

OnEarlyDataReady observes restored QUIC parameters and usable 0-RTT keys before the early connection is released. It does not authenticate the server or enable early data. The callback runs on the connection loop and must not block or reenter it; OpenUniStream and SendStream.TryWriteAll may stage bounded data. Nil removes this observer; HTTP/3's own initial-settings policy remains active.

func (*QUICSettings) OnEarlyDataRejected ΒΆ

func (q *QUICSettings) OnEarlyDataRejected(callback func(*quic.Conn)) *QUICSettings

OnEarlyDataRejected observes a TLS rejection of QUIC 0-RTT. It runs on the connection loop and must return promptly without reentering the connection. Nil removes the application observer; owned-cache rejection handling remains.

func (*QUICSettings) Pacing ΒΆ

func (q *QUICSettings) Pacing(algorithm PacingAlgorithm) *QUICSettings

Pacing selects the send scheduler independently of congestion control.

func (*QUICSettings) PacingBurstPackets ΒΆ

func (q *QUICSettings) PacingBurstPackets(packets uint32) *QUICSettings

PacingBurstPackets sets initial/idle burst credit in path-sized packets.

func (*QUICSettings) PacingGains ΒΆ

func (q *QUICSettings) PacingGains(slowStart, avoidance uint32) *QUICSettings

PacingGains sets slow-start and avoidance rate multipliers in thousandths.

func (*QUICSettings) PacingGranularity ΒΆ

func (q *QUICSettings) PacingGranularity(granularity time.Duration) *QUICSettings

PacingGranularity permits sends whose pacing delay is below this duration.

func (*QUICSettings) PacingLumpyBurst ΒΆ

func (q *QUICSettings) PacingLumpyBurst(packets, windowFraction uint32, minBandwidth uint64) *QUICSettings

PacingLumpyBurst limits scheduled bursts by packet count, window fraction (thousandths), and minimum estimated bandwidth in bytes per second.

func (*QUICSettings) PacketNumberLengthPolicy ΒΆ

func (q *QUICSettings) PacketNumberLengthPolicy(policy func(quic.PacketNumberLengthInfo) uint8) *QUICSettings

PacketNumberLengthPolicy chooses 1..4 encoded bytes per packet from live recovery state. Zero or invalid results retain native behavior; the transport increases results that cannot safely represent the unacknowledged range.

func (*QUICSettings) PacketNumberSkipping ΒΆ

func (q *QUICSettings) PacketNumberSkipping(enabled bool) *QUICSettings

PacketNumberSkipping controls random Application Data gaps. It also controls PTO gaps unless ApplicationProbeSkipPacketNumber explicitly overrides them. Peer ACK validation remains enabled.

func (*QUICSettings) PeerAckFrequencyPolicy ΒΆ

func (q *QUICSettings) PeerAckFrequencyPolicy(policy PeerAckFrequencyPolicy) *QUICSettings

PeerAckFrequencyPolicy selects outgoing legacy ACK_FREQUENCY requests after the peer advertises support. The callback receives live window, MTU and RTT state plus the last acknowledged request. Nil disables sending; local receive policy and its LegacyAckFrequency advertisement remain independent.

func (*QUICSettings) PeerPacketRecoveryPolicy ΒΆ

func (q *QUICSettings) PeerPacketRecoveryPolicy(
	policy func(quic.PeerPacketInfo) quic.PeerPacketRecovery,
) *QUICSettings

PeerPacketRecoveryPolicy selects responses to missing or retired peer keys. Authentication failures never invoke it. Nil restores native behavior.

func (*QUICSettings) PeerTransportParameters ΒΆ

func (q *QUICSettings) PeerTransportParameters(ids ...uint64) *QUICSettings

PeerTransportParameters selects unrecognized peer extension IDs to retain from each handshake. Values are available through Conn.PeerTransportParameter after verification and are not restored from session tickets. An empty list disables capture; the supplied IDs are copied.

func (*QUICSettings) PersistentCongestionThreshold ΒΆ

func (q *QUICSettings) PersistentCongestionThreshold(ptos uint32) *QUICSettings

PersistentCongestionThreshold sets the consecutive-loss duration in base PTOs. Zero preserves the engine's native behavior; a PTO expiry alone is not a loss.

func (*QUICSettings) PrioritizeFinishedStreams ΒΆ

func (q *QUICSettings) PrioritizeFinishedStreams(enabled bool) *QUICSettings

PrioritizeFinishedStreams sends queued bytes and FIN of write-closed streams alongside retransmissions before ordinary new data, retaining creation order within each class. It applies only with StreamSchedulingByCreation. Firefox enables this to match Neqo's DataSent scheduling; urgency scheduling is unchanged.

func (*QUICSettings) ProportionalRateReduction ΒΆ

func (q *QUICSettings) ProportionalRateReduction(enabled bool) *QUICSettings

ProportionalRateReduction enables RFC 6937's send allowance during recovery.

func (*QUICSettings) ReceiveBatchSize ΒΆ

func (q *QUICSettings) ReceiveBatchSize(size int) *QUICSettings

ReceiveBatchSize sets the maximum datagrams offered to one UDP batch read. Zero keeps the platform default; 1 through 255 select a capacity. Platforms and custom sockets without batch reads remain single-read. This does not combine outgoing packets or change the advertised UDP payload limit.

func (*QUICSettings) ReceiveWindowUpdateDivisor ΒΆ

func (q *QUICSettings) ReceiveWindowUpdateDivisor(divisor uint32) *QUICSettings

ReceiveWindowUpdateDivisor refreshes stream/connection credit after more than 1/divisor of its window is consumed. Zero retains native behavior; one is invalid.

func (*QUICSettings) RecoveryBurstPackets ΒΆ

func (q *QUICSettings) RecoveryBurstPackets(packets uint32) *QUICSettings

RecoveryBurstPackets permits an immediate bounded send after a new loss event.

func (*QUICSettings) RequireStreamCreditRelease ΒΆ

func (q *QUICSettings) RequireStreamCreditRelease(required bool) *QUICSettings

RequireStreamCreditRelease keeps completed peer streams counted until their credit is explicitly released. This is for applications managing incoming streams.

func (*QUICSettings) ResetAckPolicy ΒΆ

func (q *QUICSettings) ResetAckPolicy() *QUICSettings

ResetAckPolicy restores native receive ACK behavior, retaining MaxAckDelay.

func (*QUICSettings) ResetInitialPacketProtection ΒΆ

func (q *QUICSettings) ResetInitialPacketProtection() *QUICSettings

ResetInitialPacketProtection clears random Initial splits, PINGs and prefix sizing. Explicit InitialCryptoLayout and DisableClientHelloScrambling retain their independently configured values.

func (*QUICSettings) ResumeRTT ΒΆ

func (q *QUICSettings) ResumeRTT(precision time.Duration) *QUICSettings

ResumeRTT restores a measured RTT from the selected live TLS ticket, rounded down to the supplied precision. Zero disables restoration. Firefox uses whole milliseconds; this local recovery estimate does not advertise a parameter. The supported range is zero through one minute; Build rejects other values.

func (*QUICSettings) ResumeVersion ΒΆ

func (q *QUICSettings) ResumeVersion(enabled bool) *QUICSettings

ResumeVersion chooses the first QUIC version from an available session ticket previously stored by this client for the origin. Expired, evicted, unmarked and disabled-version tickets retain the configured first version. It does not reorder the caller's configuration. The Firefox profile enables this policy.

func (*QUICSettings) SeparatePacketNumberSpaces ΒΆ

func (q *QUICSettings) SeparatePacketNumberSpaces(enabled bool) *QUICSettings

SeparatePacketNumberSpaces starts Handshake and Application Data at zero, independently of Initial. 0-RTT and 1-RTT remain one space.

func (*QUICSettings) Set ΒΆ

func (q *QUICSettings) Set() *Builder

Set applies the accumulated QUIC settings and returns the main Builder.

func (*QUICSettings) SlowStart ΒΆ

func (q *QUICSettings) SlowStart(algorithm SlowStartAlgorithm) *QUICSettings

SlowStart selects classic acknowledged-byte growth or original HyStart. Native retains the engine's HyStart; Hybrid is not HyStart++.

func (*QUICSettings) SortConnectionIDFrames ΒΆ

func (q *QUICSettings) SortConnectionIDFrames(enabled bool) *QUICSettings

SortConnectionIDFrames sends queued NEW_CONNECTION_ID frames in ascending sequence order. Other control-frame types keep their native relative positions.

func (*QUICSettings) StreamDataRecovery ΒΆ

func (q *QUICSettings) StreamDataRecovery(enabled bool) *QUICSettings

StreamDataRecovery acknowledges STREAM byte ranges across all transmitted copies, including late originals and split retransmissions. Browser profiles enable it automatically; disabling retains the native frame recovery path.

func (*QUICSettings) StreamLossRetention ΒΆ

func (q *QUICSettings) StreamLossRetention(policy func(quic.StreamLossInfo) bool) *QUICSettings

StreamLossRetention selects the lifetime of lost STREAM packet ACK metadata. The callback receives transport measurements and must not block or reenter QUIC. Nil retains useful metadata up to the engine's packet tracking limit.

func (*QUICSettings) StreamReceiveWindows ΒΆ

func (q *QUICSettings) StreamReceiveWindows(bidiLocal, bidiRemote, uni uint64) *QUICSettings

StreamReceiveWindows sets initial bidirectional-local, bidirectional-remote and unidirectional receive windows. Zero explicitly advertises zero credit.

func (*QUICSettings) StreamSchedulingByCreation ΒΆ

func (q *QUICSettings) StreamSchedulingByCreation(enabled bool) *QUICSettings

StreamSchedulingByCreation drains writable streams in creation order instead of local urgency/incremental queues. Lost data retains precedence unless PrioritizeFinishedStreams groups finished writes in that same class. Blocked streams are skipped, and completed streams release bookkeeping. This mode takes precedence over StreamPriority. Firefox selects it for ordinary HTTP/3.

func (*QUICSettings) TLSClientFactory ΒΆ

func (q *QUICSettings) TLSClientFactory(factory tlsquic.NewClient) *QUICSettings

TLSClientFactory sets a custom QUIC TLS engine. Configure either this factory or ClientHelloSpec/ClientHelloFactory; using both returns an error.

func (*QUICSettings) TLSClientFactoryWrapper ΒΆ

func (q *QUICSettings) TLSClientFactoryWrapper(
	wrapper func(*quic.Conn, tlsquic.NewClient) tlsquic.NewClient,
) *QUICSettings

TLSClientFactoryWrapper decorates the native or browser TLS factory for each connection. The factory receives a private TLS config with destination and ALPN set. The wrapper must preserve session events and must not perform network I/O. HTTP/3 adds its per-ticket SETTINGS bookkeeping outside this wrapper. Nil removes the application wrapper without changing the selected TLS engine.

func (*QUICSettings) TokenStore ΒΆ

func (q *QUICSettings) TokenStore(store quic.TokenStore) *QUICSettings

TokenStore sets the shared store of address validation tokens. Nil disables it.

func (*QUICSettings) Tracer ΒΆ

func (q *QUICSettings) Tracer(tracer func(context.Context, bool, quic.ConnectionID) qlogwriter.Trace) *QUICSettings

Tracer supplies a trace recorder for each new QUIC connection.

func (*QUICSettings) TransportParameter ΒΆ

func (q *QUICSettings) TransportParameter(id uint64, value []byte) *QUICSettings

TransportParameter adds or replaces an extension parameter with wire-encoded bytes. The value is copied. Engine-owned parameters must use their own setters. Advertising a parameter does not implement an extension protocol.

func (*QUICSettings) TransportParameterOrder ΒΆ

func (q *QUICSettings) TransportParameterOrder(ids ...uint64) *QUICSettings

TransportParameterOrder sets preferred parameter order. Unlisted parameters follow in their original order. Use transportparams.Grease for native GREASE. The order is copied and also applies to layouts generated by a browser factory.

func (*QUICSettings) TransportParametersFactory ΒΆ

func (q *QUICSettings) TransportParametersFactory(
	factory func(quic.Version) (*transportparams.Layout, error),
) *QUICSettings

TransportParametersFactory supplies a layout per handshake attempt, replacing any previous factory and its edits. Later layout setters amend its result. The factory may run concurrently. Nil restores the static layout.

func (*QUICSettings) ValidatePeerTransportParameters ΒΆ

func (q *QUICSettings) ValidatePeerTransportParameters(validate func([]transportparams.Parameter) error) *QUICSettings

ValidatePeerTransportParameters checks captured peer extensions before they are accepted. The callback receives private copies, runs before authentication on the connection loop, and must not block or reenter QUIC. An error rejects the handshake with TRANSPORT_PARAMETER_ERROR. Nil clears this validation.

func (*QUICSettings) Versions ΒΆ

func (q *QUICSettings) Versions(versions ...quic.Version) *QUICSettings

Versions sets the allowed QUIC versions. The input slice is copied. An empty list selects the versions supported by quic-go.

type Request ΒΆ

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

Request represents an HTTP request with additional surf-specific functionality. It wraps the standard http.Request and provides enhanced features like middleware support, retry capabilities, remote address tracking, and structured error handling.

func (*Request) AddCookies ΒΆ

func (req *Request) AddCookies(cookies ...*http.Cookie) *Request

AddCookies adds one or more HTTP cookies to the request. Cookies are added to the request headers and will be sent with the HTTP request. Returns the request for method chaining.

func (*Request) AddHeaders ΒΆ

func (req *Request) AddHeaders(headers ...any) *Request

AddHeaders adds HTTP headers to the request, appending to any existing headers with the same name. Unlike SetHeaders, this method preserves existing headers and adds new values. Supports the same input formats as SetHeaders. Returns the request for method chaining.

func (*Request) Body ΒΆ

func (req *Request) Body(data any) *Request

Body sets the request body from various data types. Supported types include: []byte, string, g.String, g.Bytes, map[string]string, g.Map, g.MapOrd, and structs with json/xml tags. The Content-Type header is automatically detected and set based on the data. Returns the request for method chaining.

func (*Request) Do ΒΆ

func (req *Request) Do() g.Result[*Response]

Do executes the HTTP request and returns a Response wrapped in a Result type. This is the main method that performs the actual HTTP request with full surf functionality: - Applies request middleware (authentication, headers, tracing, etc.) - Preserves request body for potential retries - Implements retry logic with configurable status codes and delays - Measures request timing for performance analysis - Handles request preparation errors and write errors

func (*Request) Fetch ΒΆ

func (req *Request) Fetch() *Request

Fetch selects a browser's ordinary fetch header preset, such as an API request. GET and HEAD default to document navigation; call Fetch to use fetch defaults for Accept, Fetch Metadata and Priority instead. Other methods already default to fetch, so a normal POST API request does not need this call.

The HTTP method and body are configured by Get/Post/etc. and Body/StreamingBody. The selected scenario survives redirects, including HTTP origins where browsers omit Fetch Metadata. Explicit header values and ordered maps take precedence.

client.Get(url).Fetch().Do()

func (*Request) GetRequest ΒΆ

func (req *Request) GetRequest() *http.Request

GetRequest returns the underlying standard http.Request. Provides access to the wrapped HTTP request for advanced use cases.

func (*Request) HTTP3PriorityUpdates ΒΆ

func (req *Request) HTTP3PriorityUpdates(handler func(*HTTP3PriorityUpdater)) *Request

HTTP3PriorityUpdates calls handler after HTTP/3 request HEADERS are sent on each attempt. Return promptly; retain the updater to change priority while the response is open. HTTP/1 and HTTP/2 do not invoke the handler.

func (*Request) Multipart ΒΆ

func (req *Request) Multipart(m *Multipart) *Request

Multipart sets multipart form data for the request. The provided Multipart object contains form fields and files to be sent. Returns the request for method chaining. If m is nil, an error is set on the request.

func (*Request) Navigation ΒΆ

func (req *Request) Navigation() *Request

Navigation selects a browser's document-navigation header preset. Use it for a POST that represents form navigation rather than an API fetch: its Accept, Fetch Metadata, Priority and cache defaults can differ from ordinary POST. GET and HEAD already default to navigation and usually do not need this call.

Get/Post/etc. and Body/Multipart still configure the HTTP method and payload. The scenario survives redirects; metadata is emitted only where the browser normally sends it. Explicit header values and ordered maps take precedence.

client.Post(url).Navigation().Body("name=surf").Do()

func (*Request) SetHeaders ΒΆ

func (req *Request) SetHeaders(headers ...any) *Request

SetHeaders sets HTTP headers for the request, replacing any existing headers with the same name. Supports multiple input formats: - Two arguments: key, value (string or g.String) - Single argument: http.Header, Headers, map types, or g.Map types Maintains header order for fingerprinting purposes when using g.MapOrd. Returns the request for method chaining.

func (*Request) StreamingBody ΒΆ

func (req *Request) StreamingBody(body io.Reader, length ...int64) *Request

StreamingBody sends body without reading it into memory first. An optional length declares its size; omitted or -1 means unknown, and zero means empty. Surf owns and closes body. Blocking readers must implement Close so it unblocks Read, as required by http.Request.Body. This body is sent once: status retries, 307/308 redirects and protocol fallback need a replay factory. Cancellation and transport failure close body to release a pending read.

func (*Request) StreamingBodyFactory ΒΆ

func (req *Request) StreamingBodyFactory(factory func() (io.ReadCloser, error), length ...int64) *Request

StreamingBodyFactory creates a fresh streaming body for the initial attempt, retries, redirects and protocol fallback. No body is buffered. The factory is called when sending, must return a new non-nil reader on each call, and must be concurrency safe. Length follows StreamingBody; a zero-length body does not call the factory. Surf owns every reader returned by the factory.

func (*Request) WithContext ΒΆ

func (req *Request) WithContext(ctx context.Context) *Request

WithContext associates a context with the request for cancellation and deadlines. The context can be used to cancel the request, set timeouts, or pass request-scoped values. Returns the request for method chaining. If ctx is nil, the request is unchanged.

type Response ΒΆ

type Response struct {
	Headers   Headers  // Response headers with convenience methods
	Cookies   Cookies  // Response cookies with enhanced functionality
	UserAgent g.String // User agent that was used for the request
	Proto     g.String // HTTP protocol version (HTTP/1.1, HTTP/2, HTTP/3)

	*Client          // Embedded client provides access to all client functionality
	URL     *url.URL // Final URL after following redirects

	Body *Body // Enhanced response body with compression support and caching

	Time          time.Duration // Total request duration including retries
	ContentLength int64         // Content-Length header value (-1 if not specified)
	StatusCode    StatusCode    // HTTP status code with convenience methods
	Attempts      int           // Number of retry attempts made for this request
	// contains filtered or unexported fields
}

Response represents an HTTP response with enhanced functionality and metadata. It wraps the standard http.Response and provides additional features like timing information, retry attempts tracking, enhanced cookie management, and convenient access methods.

func (Response) Debug ΒΆ

func (resp Response) Debug() *Debug

Debug returns a debug instance associated with a Response.

func (Response) GetCookies ΒΆ

func (resp Response) GetCookies(rawURL g.String) []*http.Cookie

GetCookies returns all cookies from the response that would be sent to the specified URL. Filters cookies based on domain, path, and security attributes.

func (Response) GetResponse ΒΆ

func (resp Response) GetResponse() *http.Response

GetResponse returns the underlying standard http.Response. Provides access to the wrapped HTTP response for advanced use cases.

func (Response) Location ΒΆ

func (resp Response) Location() g.String

Location returns the HTTP Location header value, typically used in redirects. Contains the URL that the client should redirect to for 3xx status codes.

func (Response) Referer ΒΆ

func (resp Response) Referer() g.String

Referer returns the HTTP Referer header value from the original request. This indicates which page linked to the resource being requested.

func (Response) RemoteAddress ΒΆ

func (resp Response) RemoteAddress() net.Addr

RemoteAddress returns the network address of the server that sent this response. Useful for logging, debugging, or connection analysis.

func (*Response) SetCookies ΒΆ

func (resp *Response) SetCookies(rawURL g.String, cookies []*http.Cookie) error

SetCookies stores cookies in the client's cookie jar for the specified URL. This allows the cookies to be automatically sent with future requests to matching URLs.

func (Response) TLSGrabber ΒΆ

func (resp Response) TLSGrabber() *TLSData

TLSGrabber extracts TLS connection information from the response. Returns detailed TLS connection data including certificates, cipher suites, and protocol version if the response was received over a TLS connection. Returns nil for non-TLS connections.

type SessionCache ΒΆ

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

SessionCache configures TLS ticket caching through the client builder. Settings apply to TCP and QUIC by default; TCP, QUIC and Both select the transports affected by subsequent settings. Set returns the parent builder. Session separately enables cookie persistence.

func (*SessionCache) Both ΒΆ

func (s *SessionCache) Both() *SessionCache

Both applies subsequent settings to TCP and QUIC caches.

func (*SessionCache) Brotli ΒΆ

func (s *SessionCache) Brotli(quality int) *SessionCache

Brotli selects ticket compression quality 0..11; -1 disables compression. Firefox uses quality 1. Compressed records use Go's public session format, so their exact charged size differs from Firefox's NSS representation.

func (*SessionCache) ByteCapacity ΒΆ

func (s *SessionCache) ByteCapacity(bytes int) *SessionCache

ByteCapacity bounds charged queued-record bytes, from zero to 1 GiB. Zero disables the byte bound. Firefox defaults to 8 MiB; other profiles leave it disabled. Keys are charged per ticket; object overhead and consumed identities are excluded. Custom caches control their own storage.

func (*SessionCache) Capacity ΒΆ

func (s *SessionCache) Capacity(keys int) *SessionCache

Capacity bounds server keys, including recently consumed-ticket records. The valid range is 1..1048576. The generic default is 64; the Chrome/Firefox policies use 1024. Custom caches control their own limits.

func (*SessionCache) ClearEarlyDataOnReject ΒΆ

func (s *SessionCache) ClearEarlyDataOnReject(enabled bool) *SessionCache

ClearEarlyDataOnReject disables early data on remaining QUIC tickets after rejection, while retaining ordinary TLS resumption. Enabled by the Chrome QUIC policy; disabled by the generic and Firefox policies.

func (*SessionCache) Clock ΒΆ

func (s *SessionCache) Clock(clock func() time.Time) *SessionCache

Clock overrides ticket validity time. By default the cache uses TLSConfig.Time. Nil selects time.Now. This does not change the TLS engine's clock.

func (*SessionCache) Custom ΒΆ

func (s *SessionCache) Custom(cache tls.ClientSessionCache) *SessionCache

Custom supplies an application cache for the selected transports. Its policy takes precedence over browser defaults and queue settings. Nil disables the selected caches. Native and browser TCP use a separate "tcp:" key namespace.

func (*SessionCache) DiscardOnExpiry ΒΆ

func (s *SessionCache) DiscardOnExpiry(enabled bool) *SessionCache

DiscardOnExpiry removes the entire key when its next ticket expires. Otherwise individual expiry handling follows SkipExpired. The Chrome QUIC policy enables whole-entry expiry; the generic and Firefox policies do not.

func (*SessionCache) EvictionPolicy ΒΆ

func (s *SessionCache) EvictionPolicy(policy SessionCacheEviction) *SessionCache

EvictionPolicy selects byte-pressure eviction. Firefox removes individual tickets nearest expiry; other profiles default to least recently used keys.

func (*SessionCache) Group ΒΆ

func (s *SessionCache) Group(group func(*tls.ClientSessionState) string) *SessionCache

Group invalidates older tickets when the returned compatibility group changes. The callback runs outside cache locks and must be concurrency safe; it must not modify the supplied session. Nil disables compatibility grouping.

func (*SessionCache) Order ΒΆ

func (s *SessionCache) Order(order SessionTicketOrder) *SessionCache

Order selects the next ticket. Chrome and the generic cache select newest first; Firefox selects the nearest expiry, with new equal-expiry tickets first.

func (*SessionCache) QUIC ΒΆ

func (s *SessionCache) QUIC() *SessionCache

QUIC selects the HTTP/3 TLS cache for subsequent settings.

func (*SessionCache) ReuseTLS12 ΒΆ

func (s *SessionCache) ReuseTLS12(enabled bool) *SessionCache

ReuseTLS12 keeps legacy tickets reusable. TLS 1.3 tickets are consumed once. Enabled by the Chrome TCP policy; disabled by the other current policies.

func (*SessionCache) Set ΒΆ

func (s *SessionCache) Set() *Builder

Set applies the accumulated policy and returns the client builder. Invalid capacities or ordering are returned by Builder.Build. Caching does not enable cookie persistence or override TLSConfig.SessionTicketsDisabled.

func (*SessionCache) Shared ΒΆ

func (s *SessionCache) Shared(enabled bool) *SessionCache

Shared selects one owned TCP/QUIC cache and byte budget. Firefox enables it by default; Chrome keeps independent queues. Key namespaces remain separate. Explicit TCP/QUIC policy settings default to independent caches. Shared(true) with such settings is rejected: use Both for a common policy or Shared(false). A profile with distinct TCP/QUIC defaults cannot enable sharing. Application-supplied caches retain their own ownership and policy.

func (*SessionCache) SkipExpired ΒΆ

func (s *SessionCache) SkipExpired(enabled bool) *SessionCache

SkipExpired continues lookup after removing an expired ticket. False returns a miss and leaves the next ticket for a later connection. DiscardOnExpiry takes precedence when enabled.

func (*SessionCache) TCP ΒΆ

func (s *SessionCache) TCP() *SessionCache

TCP selects the HTTP/1 and HTTP/2 TLS cache for subsequent settings.

func (*SessionCache) TLS12TicketPolicy ΒΆ

func (s *SessionCache) TLS12TicketPolicy(policy func(TLS12TicketMetadata) TLS12TicketValidity) *SessionCache

TLS12TicketPolicy sets legacy ticket policy using authenticated engine facts. It runs once per insertion, outside cache locks, and must be concurrency safe. Missing metadata is a miss; nil restores generic certificate-bounded caching. TLS 1.3 and application-supplied caches retain their own policy.

func (*SessionCache) TicketsPerKey ΒΆ

func (s *SessionCache) TicketsPerKey(tickets int) *SessionCache

TicketsPerKey bounds available tickets for each TLS cache key, in 1..1024. The generic default is one; Chrome keeps two and Firefox keeps ten.

type SessionCacheEviction ΒΆ

type SessionCacheEviction = tlscache.EvictionPolicy

SessionCacheEviction selects which state is removed under byte pressure.

type SessionTicketOrder ΒΆ

type SessionTicketOrder = tlscache.Order

SessionTicketOrder selects the next available ticket for a connection.

type SlowStartAlgorithm ΒΆ

type SlowStartAlgorithm = quic.SlowStartAlgorithm

type StatusCode ΒΆ

type StatusCode int

StatusCode represents an HTTP status code with convenient classification methods. Extends the basic integer status code with methods to easily identify the response category.

func (StatusCode) IsClientError ΒΆ

func (s StatusCode) IsClientError() bool

IsClientError returns true if the status code indicates a client error [400, 500].

func (StatusCode) IsInformational ΒΆ

func (s StatusCode) IsInformational() bool

IsInformational returns true if the status code is in the informational range [100, 200].

func (StatusCode) IsRedirection ΒΆ

func (s StatusCode) IsRedirection() bool

IsRedirection returns true if the status code indicates a redirection [300, 400].

func (StatusCode) IsServerError ΒΆ

func (s StatusCode) IsServerError() bool

IsServerError returns true if the status code indicates a server error [500, ∞].

func (StatusCode) IsSuccess ΒΆ

func (s StatusCode) IsSuccess() bool

IsSuccess returns true if the status code indicates a successful response [200, 300].

func (StatusCode) Text ΒΆ

func (s StatusCode) Text() string

Text returns the textual representation of the status code.

type StreamReader ΒΆ

type StreamReader struct {
	*bufio.Reader
	// contains filtered or unexported fields
}

StreamReader wraps bufio.Reader with Close support.

func (*StreamReader) Close ΒΆ

func (s *StreamReader) Close() error

Close closes the underlying body.

type TCPKeepAliveInfo ΒΆ

type TCPKeepAliveInfo = profiles.TCPKeepAliveInfo

TCPKeepAliveInfo describes a Surf-owned TCP socket and negotiated protocol.

type TCPKeepAliveOptions ΒΆ

type TCPKeepAliveOptions = profiles.TCPKeepAliveOptions

TCPKeepAliveOptions selects initial keepalive and an optional timed transition.

type TLS12TicketMetadata ΒΆ

type TLS12TicketMetadata = tlscache.TLS12TicketMetadata

TLS12TicketMetadata contains authenticated issuance times and session lineage.

type TLS12TicketValidity ΒΆ

type TLS12TicketValidity = tlscache.TLS12TicketValidity

TLS12TicketValidity controls legacy ticket retention and wire-offer bounds.

type TLSData ΒΆ

type TLSData struct {
	CommonName               []string // List of common names associated with the certificate.
	DNSNames                 []string // List of DNS names associated with the certificate.
	Emails                   []string // List of email addresses associated with the certificate.
	IssuerCommonName         []string // List of common names of the certificate issuer.
	IssuerOrg                []string // List of organizations of the certificate issuer.
	Organization             []string // List of organizations associated with the certificate.
	ExtensionServerName      string   // Server name extension of the TLS certificate.
	FingerprintSHA256        string   // SHA-256 fingerprint of the certificate.
	FingerprintSHA256OpenSSL string   // SHA-256 fingerprint compatible with OpenSSL.
	TLSVersion               string   // TLS version used.
}

TLSData represents information about a TLS certificate.

type TransportAdapter ΒΆ

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

TransportAdapter adapts surf.Client to net/http.RoundTripper It uses the full surf pipeline including middleware

func (*TransportAdapter) CloseIdleConnections ΒΆ

func (s *TransportAdapter) CloseIdleConnections()

func (*TransportAdapter) RoundTrip ΒΆ

func (s *TransportAdapter) RoundTrip(req *_http.Request) (*_http.Response, error)

RoundTrip implements net/http.RoundTripper interface using surf's full pipeline

Directories ΒΆ

Path Synopsis
examples
async/async_get command
auth/basic_auth command
cache/cache command
compression command
context command
cookies command
debug command
dns/custom_dns command
file_upload command
headers/headers command
headers/presets command
http/get command
http/h2c command
http/head command
http/http1 command
http/http2 command
http/http3 command
http/http3_rtt command
ja_hello/chrome command
keep_alive command
limiter command
md5 command
middleware command
multipart command
network command
no_redirect command
post command
proxy/rotating command
proxy/simple command
raw command
redirect command
remote_address command
retry command
session command
split_request command
sse command
std/std command
std/std_cookies command
stream command
timeout command
tls command
tls/ech command
unix_socket command
user_agent command
utf8 command
internal
alps
Package alps decodes authenticated application-layer protocol settings.
Package alps decodes authenticated application-layer protocol settings.
clientdialer
Package clientdialer identifies Surf's default TCP dial functions.
Package clientdialer identifies Surf's default TCP dial functions.
connrace
Package connrace coordinates connection preparation without sending requests.
Package connrace coordinates connection preparation without sending requests.
echretry
Package echretry carries authenticated ECH retry metadata for one connection attempt.
Package echretry carries authenticated ECH retry metadata for one connection attempt.
http3
Package h3transport owns HTTP/3 execution and authenticated alternative routing.
Package h3transport owns HTTP/3 execution and authenticated alternative routing.
netchange
Package netchange delivers native network notifications to built clients.
Package netchange delivers native network notifications to built clients.
origin
Package origin supplies shared HTTP origin classification for browser policies.
Package origin supplies shared HTTP origin classification for browser policies.
quic
Package quictransport owns UDP sockets and QUIC connection establishment.
Package quictransport owns UDP sockets and QUIC connection establishment.
quictls
Package quictls adapts the uTLS QUIC API to the transport's event interface.
Package quictls adapts the uTLS QUIC API to the transport's event interface.
retryafter
Package retryafter parses values of the HTTP Retry-After header as defined by RFC 7231 Β§7.1.3.
Package retryafter parses values of the HTTP Retry-After header as defined by RFC 7231 Β§7.1.3.
specclone
Package specclone provides deep cloning functionality for uTLS ClientHelloSpec structures.
Package specclone provides deep cloning functionality for uTLS ClientHelloSpec structures.
tlsstate
Package tlsstate adapts public TLS state across the standard and uTLS APIs.
Package tlsstate adapts public TLS state across the standard and uTLS APIs.
pkg
quicconn
Package quicconn provides a net.PacketConn adapter for feeding QUIC stacks (such as quic-go) with datagrams originating from a generic net.Conn.
Package quicconn provides a net.PacketConn adapter for feeding QUIC stacks (such as quic-go) with datagrams originating from a generic net.Conn.
sse
tlscache
Package tlscache provides bounded TLS ticket queues for browser profiles and applications.
Package tlscache provides bounded TLS ticket queues for browser profiles and applications.
Package profiles defines the shared variant contract used by browser profile packages (profiles/chrome, profiles/firefox, ...) and consumed by the top-level surf package.
Package profiles defines the shared variant contract used by browser profile packages (profiles/chrome, profiles/firefox, ...) and consumed by the top-level surf package.
internal/ech
Package ech contains wire helpers shared by browser-owned ECH policies.
Package ech contains wire helpers shared by browser-owned ECH policies.
tests
internal/alpspeer
Package alpspeer supplies an authenticated test-only QUIC TLS transcript peer.
Package alpspeer supplies an authenticated test-only QUIC TLS transcript peer.
internal/echcapture
Package echcapture reads captured TLS messages without retaining live tickets in public reference files.
Package echcapture reads captured TLS messages without retaining live tickets in public reference files.
internal/wiretest
Package wiretest normalizes serialized browser handshakes for golden tests.
Package wiretest normalizes serialized browser handshakes for golden tests.
tools/echresumption command
echresumption verifies private captured pairs and writes sanitized references.
echresumption verifies private captured pairs and writes sanitized references.
tools/sessioncache command
The sessioncache command serves a trusted-profile cache-pressure fixture.
The sessioncache command serves a trusted-profile cache-pressure fixture.

Jump to

Keyboard shortcuts

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