Awesome Go

surf

CategoryNetworking
SubcategoryHTTP Clients
Stars1,853

Advanced HTTP client with HTTP/1.1, HTTP/2, HTTP/3 (QUIC), SOCKS5 proxy support and browser-grade TLS fingerprinting

About surf

This large README is shown as a plain-text preview. Read the full README at the source

<p align="center">
  <img src="https://user-images.githubusercontent.com/65846651/233453773-33f38b64-0adc-41b4-8e13-a49c89bf9db6.png">
</p>

<h1>Surf - Advanced HTTP Client for Go</h1>

[![Go Reference](https://pkg.go.dev/badge/github.com/enetx/surf.svg)](https://pkg.go.dev/github.com/enetx/surf)
[![Coverage Status](https://coveralls.io/repos/github/enetx/surf/badge.svg?branch=main&service=github)](https://coveralls.io/github/enetx/surf?branch=main)
[![Go](https://github.com/enetx/surf/actions/workflows/go.yml/badge.svg)](https://github.com/enetx/surf/actions/workflows/go.yml)
[![Mentioned in Awesome Go](https://awesome.re/mentioned-badge.svg)](https://github.com/avelino/awesome-go)
[![Ask DeepWiki](https://img.shields.io/badge/Ask-DeepWiki-2f80ed)](https://deepwiki.com/enetx/surf)

<p>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.</p>

## ✨ 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](https://github.com/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

```bash
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`.

```go
// 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.

```go
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

```go
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

```go
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](tests/testdata/wire/chrome_158/README.md) 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.

```go
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`, and origin-cache `Capacity`, `Lifetime`, `Clock`
and `Enabled`. 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](examples/headers/client_hints/client_hints.go) and
[independent Chromium reference](tests/testdata/wire/client_hints/README.md).
Negotiation observes HTTP headers on document navigations; DOM meta directives,
frame permissions, disk persistence and ALPS hint frames are separate scopes.

`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](tests/testdata/wire/README.md) 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](profiles/chrome/common/headers.go) and
[Firefox](profiles/firefox/common/headers.go). 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`](profiles/header_context.go). 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:

```go
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](examples/headers/presets/presets.go)
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](tests/testdata/wire/header_presets/README.md) 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

```go
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

```go
// 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

```go
// 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

```go
// 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

```go
// 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](tests/testdata/wire/chrome_158/README.md).

### 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.

```go
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](https://github.com/chromium/chromium/blob/158.0.8127.18/DEPS)
and [Firefox 160.0](https://github.com/mozilla-firefox/firefox/tree/FIREFOX_160_0_RELEASE).
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](tests/testdata/wire/qpack/README.md) 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](examples/http/http2_custom/http2_custom.go) and
[HTTP/3 custom example](examples/http/http3_custom/http3_custom.go) 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;

Frequently Asked Questions

What is surf?

surf is a Networking library for the Go programming language. Advanced HTTP client with HTTP/1.1, HTTP/2, HTTP/3 (QUIC), SOCKS5 proxy support and browser-grade TLS fingerprinting

How many GitHub stars does surf have?

surf has 1,853 GitHub stars in the directory's latest synchronization.

How do I install surf?

Install surf with the Go module system using `go get enetx/surf`. Check the repository for the current installation instructions.

What category does surf belong to?

surf is listed under Networking, specifically HTTP Clients.

← Back to HTTP Clients