transport

package
v0.0.0-...-695b9c6 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: MIT Imports: 16 Imported by: 0 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.

Documentation

Overview

./internal/transport/proxy.go

Index

Constants

View Source
const DefaultMaxBodyBuffer int64 = 4 * 1024 * 1024

DefaultMaxBodyBuffer — максимальный размер тела запроса (4 МБ), который буферизируется в памяти для безопасного повтора.

Variables

View Source
var DefaultRetryConfig = RetryConfig{
	MaxAttempts:   3,
	BaseDelay:     300 * time.Millisecond,
	MaxDelay:      10 * time.Second,
	RetryOnCodes:  []int{429, 500, 502, 503, 504},
	MaxBodyBuffer: DefaultMaxBodyBuffer,
}

DefaultRetryConfig — сбалансированная конфигурация по умолчанию.

Functions

func ProxyFromContext

func ProxyFromContext(ctx context.Context) (string, bool)

ProxyFromContext извлекает прокси из контекста запроса.

func WithProxy

func WithProxy(ctx context.Context, proxyURI string) context.Context

WithProxy прикрепляет прокси к контексту конкретного запроса. URI формат: "http://user:pass@host:port" или "socks5://host:port".

Types

type ClientFactory

type ClientFactory func(proxyURI string) (tlsclient.HttpClient, error)

ClientFactory создает новый инстанс tlsclient.HttpClient под указанный прокси.

type HeaderFactory

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

HeaderFactory генерирует согласованные заголовки под конкретную версию браузера.

func NewHeaderFactory

func NewHeaderFactory(ver types.BrowserVersion, bType types.BrowserType) *HeaderFactory

NewHeaderFactory создает новую фабрику заголовков для сессии.

func (*HeaderFactory) ApplyHeaders

func (h *HeaderFactory) ApplyHeaders(fReq *fhttp.Request, stdReq *http.Request)

ApplyHeaders накладывает браузерные заголовки и строгий порядок следования на fhttp.Request.

func (*HeaderFactory) SecChUa

func (h *HeaderFactory) SecChUa() string

SecChUa формирует значение заголовка sec-ch-ua.

func (*HeaderFactory) UserAgent

func (h *HeaderFactory) UserAgent() string

UserAgent возвращает строку User-Agent.

type ProxyRotator

type ProxyRotator interface {
	NextProxy() string
}

ProxyRotator интерфейс для динамического выбора прокси.

type RequestType

type RequestType int

RequestType определяет контекст запроса для формирования Sec-Fetch заголовков.

const (
	RequestTypeNavigate RequestType = iota // переход пользователя на HTML страницу
	RequestTypeFetch                       // AJAX / Fetch / API запрос (JSON, subresource)
)

type RetryConfig

type RetryConfig struct {
	MaxAttempts        int           // Количество повторных попыток (0 = выключено)
	BaseDelay          time.Duration // Начальная задержка
	MaxDelay           time.Duration // Верхний предел задержки
	RetryOnCodes       []int         // HTTP-статусы для повтора (например: 429, 500, 502, 503, 504)
	MaxBodyBuffer      int64         // Лимит буфера памяти (0 = дефолт 4МБ, -1 = отключить буферизацию)
	Rotator            ProxyRotator  // Опциональный пул прокси для смены IP при ретрае
	RotateProxyOnRetry bool          // Менять ли прокси при каждой повторной попытке
}

RetryConfig задает политику повтора запросов.

type RetryTransport

type RetryTransport struct {
	Inner  http.RoundTripper
	Config RetryConfig
}

func (*RetryTransport) RoundTrip

func (r *RetryTransport) RoundTrip(req *http.Request) (*http.Response, error)

type RoundRobinProxyRotator

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

RoundRobinProxyRotator простая и быстрая потокобезопасная реализация round-robin пула.

func NewRoundRobinProxyRotator

func NewRoundRobinProxyRotator(proxies []string) *RoundRobinProxyRotator

NewRoundRobinProxyRotator создает ротатор из списка адресов.

func (*RoundRobinProxyRotator) Add

func (r *RoundRobinProxyRotator) Add(proxyURI string)

Add добавляет новый прокси в ротацию на лету.

func (*RoundRobinProxyRotator) Len

func (r *RoundRobinProxyRotator) Len() int

Len возвращает количество прокси в пуле.

func (*RoundRobinProxyRotator) NextProxy

func (r *RoundRobinProxyRotator) NextProxy() string

NextProxy возвращает следующий прокси по кругу.

type TLSTransport

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

TLSTransport реализует http.RoundTripper с поддержкой пула прокси и гарантирует консистентность браузерного отпечатка.

func NewTLSTransport

func NewTLSTransport(defaultClient tlsclient.HttpClient, factory ClientFactory, headers *HeaderFactory) *TLSTransport

NewTLSTransport создает транспорт с поддержкой пула прокси.

func (*TLSTransport) RoundTrip

func (t *TLSTransport) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip выполняет конвертацию запроса, применяет контекстный прокси и браузерные заголовки.

Jump to

Keyboard shortcuts

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