plow

package module
v1.0.6 Latest Latest
Warning

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

Go to latest
Published: Sep 18, 2025 License: MIT Imports: 25 Imported by: 0

README ΒΆ

Plow

tag Test Status GoDoc License

πŸ¦β€β¬› plow - All in One HTTP package for Go. Tuned for high performance, easy to use and speed up writing.

πŸ“¦ Installation

go get github.com/oesand/plow

🎯 Example

Client
import (
    "github.com/oesand/plow"
    "github.com/oesand/plow/specs"
)

url := specs.MustParseUrl("http://example.com")
req := plow.TextRequest(specs.HttpMethodPost, url, specs.ContentTypePlain, "Hello")

client := plow.Client{}
// Recommended (with optimal parameters)
// client := plow.DefaultClient()

resp, err := client.Make(req)
if err != nil {
    panic(err)
}
client := plow.Client{}

// You can use proxy
transport := &plow.Transport{}
transport.Proxy = func(url *specs.Url) (*specs.Url, error) {
    return specs.ParseUrl("socks5://127.0.0.1:1080")
}

// Fixed proxy url
transport.Proxy = plow.FixedProxyUrl(specs.MustParseUrl("https://127.0.0.1"))
client.Transport = transport
Server
import (
    "github.com/oesand/plow"
    "github.com/oesand/plow/specs"
)

handler := plow.HandlerFunc(func(ctx context.Context, request plow.Request) plow.Response {
    return plow.TextResponse(specs.StatusCodeOK, specs.ContentTypePlain, "hello", func(resp plow.Response) {
        resp.Header().Set("X-Hello", "Value")
        resp.Header().SetCookieValue("Name", "Value")
    })
})

server := plow.Server{
    Handler: handler,
}

// Recommended (with optimal parameters)
// server := plow.DefaultServer(handler)

err := server.ListenAndServe(":http")
if err != nil {
    panic(err)
}

Documentation ΒΆ

Index ΒΆ

Constants ΒΆ

View Source
const (
	// DefaultServerName default value for Server.ServerName parameter
	DefaultServerName = "plow"

	// DefaultMaxRedirectCount default value for Client.MaxRedirectCount parameter
	DefaultMaxRedirectCount int = 10

	// DefaultMaxEncodingSize default value for Server.MaxEncodingSize parameter
	DefaultMaxEncodingSize int64 = 5 << 20 // 5 mb
)

Variables ΒΆ

This section is empty.

Functions ΒΆ

func FixedProxyUrl ΒΆ

func FixedProxyUrl(url *specs.Url) func(*specs.Url) (*specs.Url, error)

FixedProxyUrl returns a proxy function (for use in a Transport) that always returns the same URL.

func MultipartReader ΒΆ

func MultipartReader(req Request) (*multipart.Reader, error)

MultipartReader creates a new multipart.Reader for the given request. It validates the request's Content-Type header to ensure it is a valid multipart type and extracts the boundary parameter required for parsing the multipart body.

func ReadForm ΒΆ

func ReadForm(req Request) (specs.Query, error)

ReadForm reads and parses the request body as a form if Content-Type is specs.ContentTypeForm.

func ReadJson ΒΆ

func ReadJson[T any](reqOrResp any) (*T, error)

ReadJson reads a JSON object from a Request or ClientResponse. The reqOrResp parameter is the Request or ClientResponse to read from. The T parameter is the type of the JSON object to read. The function returns the JSON object and an error if the request or response is not a JSON object.

func ShortResponseWriter ΒΆ

func ShortResponseWriter(code specs.StatusCode, text string) io.WriterTo

ShortResponseWriter creates an io.WriterTo implementation that writes a short HTTP error response. initialized with the provided status code and text.

This is useful for quickly generating responses in HTTP handlers, ensuring consistent formatting and status codes across the application. The returned object implements io.WriterTo, allowing it to be written directly to an io.Writer, such as net.Conn.

Types ΒΆ

type BodyWriter ΒΆ

type BodyWriter interface {
	// WriteBody function allows you to send a content body to a specific node.
	WriteBody(io.Writer) error

	// ContentLength specifies size of the body
	// which can be passed in the 'Content-Length' header.
	ContentLength() int64
}

BodyWriter is an interface representing the ability to send bytes of the HTTP server response body or client request body.

type Client ΒΆ

type Client struct {
	// Transport specifies the mechanism by which individual HTTP requests are made.
	// If nil, [DefaultTransport] is used.
	Transport RoundTripper

	// MaxRedirectCount maximum number of redirects
	// before getting an error.
	// if not specified is used [DefaultMaxRedirectCount]
	MaxRedirectCount int

	// Header specifies independent request header and cookies
	//
	// The Header is used to insert headers and cookies
	// into every outbound Request independent of url.
	// The Header is consulted for every redirect that the [Client] follows.
	//
	// If Header is nil, headers and cookies are only sent
	// if they are explicitly set on the [Request].
	Header *specs.Header

	// Jar specifies the cookie jar with dependent to url
	//
	// The Jar is used to insert relevant requested url cookies
	// into every outbound Request and is updated
	// with the cookie values of every inbound Response.
	// The Jar is consulted for every redirect that the [Client] follows.
	//
	// If Jar is nil, cookies are only sent
	// if they are explicitly set on the [Request].
	Jar *specs.CookieJar
	// contains filtered or unexported fields
}

A Client is an HTTP client. Its zero value of DefaultClient.

A Client is higher-level than a RoundTripper (such as Transport) and additionally handles HTTP details such as cookies and redirects.

func DefaultClient ΒΆ

func DefaultClient() *Client

DefaultClient factory for creating Client with optimal parameters for perfomance and safety

Each call creates a new instance of Client

func (*Client) Make ΒΆ

func (cln *Client) Make(request ClientRequest) (ClientResponse, error)

Make sends an HTTP request and returns an HTTP response, following policy (such as redirects, cookies, auth) as configured on the client.

An error is returned if caused by client policy or failure to speak HTTP (such as a network connectivity problem).

A non-2xx status code doesn't cause an error.

func (*Client) MakeContext ΒΆ

func (cln *Client) MakeContext(ctx context.Context, request ClientRequest) (ClientResponse, error)

MakeContext version Client.Make with context.Context cancellation support

type ClientRequest ΒΆ

type ClientRequest interface {
	// Method specifies the HTTP method (GET, POST, PUT, etc.)
	// to be sent by the client in HTTP request.
	Method() specs.HttpMethod

	// Url specifies the URL for client requests.
	Url() *specs.Url

	// Header contains the request header fields and cookies
	// to be sent by the client in HTTP request.
	Header() *specs.Header
}

ClientRequest is an interface for the HTTP response sent by the Client and RoundTripper (such as Transport).

func BufferRequest ΒΆ

func BufferRequest(method specs.HttpMethod, url *specs.Url, contentType string, buffer []byte) ClientRequest

BufferRequest is implementation for the ClientRequest with []byte as request body to be sent by the Client or Transport.

Content type applies as "Content-Type" header value

if method unspecified then specs.HttpMethodPost will be set if content type unspecified then specs.ContentTypeRaw will be set

func EmptyRequest ΒΆ

func EmptyRequest(method specs.HttpMethod, url *specs.Url) ClientRequest

EmptyRequest is implementation for the ClientRequest without body to be sent by the Client.

if method unspecified then specs.HttpMethodGet will be set

func FormRequest ΒΆ

func FormRequest(method specs.HttpMethod, url *specs.Url, form specs.Query) ClientRequest

FormRequest creates a ClientRequest with the specified HTTP method, URL, and form data encoded as application/x-www-form-urlencoded. Sets the Content-Type header to specs.ContentTypeForm.

If the method is not specified, defaults to POST. The method must support a request body.

func JsonRequest ΒΆ

func JsonRequest(method specs.HttpMethod, url *specs.Url, body any) (ClientRequest, error)

JsonRequest returns a ClientRequest that can be used to send a JSON request. The body parameter is the JSON object to be sent in the request.

func MultipartRequest ΒΆ

func MultipartRequest(method specs.HttpMethod, url *specs.Url, filler func(*multipart.Writer) error) ClientRequest

MultipartRequest creates a new ClientRequest for sending a multipart HTTP request. It sets the appropriate Content-Type header with a generated boundary and uses the provided filler function to populate the multipart body.

filler is a function that takes a *multipart.Writer and writes the necessary parts to it. multipart.Writer.Close must not be called by the filler function, as it will be handled by the request itself. Chunked transfer encoding is enabled by default for this request.

If the method is not specified, it defaults to POST.

func StreamRequest ΒΆ

func StreamRequest(method specs.HttpMethod, url *specs.Url, contentType string, stream io.Reader, contentLength int64) ClientRequest

StreamRequest is implementation for the ClientRequest that copy response body from io.Reader to be sent by the Client or Transport.

Content type applies as "Content-Type" header value

if method unspecified then specs.HttpMethodPost will be set if content type unspecified then specs.ContentTypeRaw will be set

func TextRequest ΒΆ

func TextRequest(method specs.HttpMethod, url *specs.Url, contentType string, text string) ClientRequest

TextRequest is implementation for the ClientRequest with string as request body to be sent by the Client or Transport.

Content type applies as "Content-Type" header value

if method unspecified then specs.HttpMethodPost will be set if content type unspecified then specs.ContentTypePlain will be set

type ClientResponse ΒΆ

type ClientResponse interface {
	// StatusCode specifies [specs.StatusCode] which
	// is received by the client.
	StatusCode() specs.StatusCode

	// Header contains the request header fields and cookies
	// which is received by the client.
	Header() *specs.Header

	// Body specifies [io.ReadCloser] response body
	// which is received by the client.
	//
	// if response body not provided return nil.
	Body() io.ReadCloser
}

ClientResponse is an interface for an HTTP request received by the Client and RoundTripper (such as Transport).

type Dialer ΒΆ

type Dialer interface {
	// Dial connects to the address on the named network.
	Dial(ctx context.Context, network, address string) (net.Conn, error)
}

Dialer is an interface representing the ability to connection over network to address.

type DialerFunc ΒΆ

type DialerFunc func(ctx context.Context, network, address string) (net.Conn, error)

DialerFunc shorthand implementation for Dialer

func (DialerFunc) Dial ΒΆ

func (f DialerFunc) Dial(ctx context.Context, network, address string) (net.Conn, error)

Dial triggers top level function DialerFunc

type ErrorHandler ΒΆ

type ErrorHandler interface {
	HandleError(ctx context.Context, conn net.Conn, err any)
}

ErrorHandler is an interface representing the ability to handle errors that occur during the processing of a request by a Server.

type ErrorHandlerFunc ΒΆ

type ErrorHandlerFunc func(ctx context.Context, conn net.Conn, err any)

ErrorHandlerFunc shorthand implementation for ErrorHandler

func (ErrorHandlerFunc) HandleError ΒΆ

func (f ErrorHandlerFunc) HandleError(ctx context.Context, conn net.Conn, err any)

HandleError triggers top level function ErrorHandlerFunc

type Handler ΒΆ

type Handler interface {
	Handle(ctx context.Context, request Request) Response
}

Handler serve HTTP Server requests and answer it

type HandlerFunc ΒΆ

type HandlerFunc func(ctx context.Context, request Request) Response

HandlerFunc shorthand implementation for Handler

func (HandlerFunc) Handle ΒΆ

func (f HandlerFunc) Handle(ctx context.Context, request Request) Response

Handle triggers top level function HandlerFunc

type HijackHandler ΒΆ

type HijackHandler = server_ops.HijackHandler

HijackHandler function that allow an Handler to take over the connection.

type MarshallResponse ΒΆ

type MarshallResponse interface {
	Response
	BodyWriter
	Instance() any
}

MarshallResponse is an interface that combines Response and BodyWriter capabilities with the ability to provide an instance of the underlying response type.

func JsonResponse ΒΆ

func JsonResponse(statusCode specs.StatusCode, body any, configure ...func(Response)) MarshallResponse

JsonResponse returns a MarshallResponse that can be used to send a JSON response. The body parameter is the JSON object to be sent in the response.

type NextProtoHandler ΒΆ

type NextProtoHandler func(conn *tls.Conn)

NextProtoHandler function to take over ownership of the provided TLS connection when an ALPN protocol upgrade has occurred.

type Request ΒΆ

type Request interface {
	// ProtoVersion specifies protocol version of incoming server request.
	ProtoVersion() (major, minor uint16)

	// RemoteAddr specifies client [net.Addr] of incoming server request.
	RemoteAddr() net.Addr

	// Hijack lets the handler take over the connection.
	// After a call to Hijack the HTTP server library
	// will not do anything else with the connection when HTTP transaction ends.
	Hijack(handler HijackHandler)

	// Method specifies the HTTP method (GET, POST, PUT, etc.)
	// of incoming server request.
	Method() specs.HttpMethod

	// Url specifies the URL of incoming server request.
	Url() *specs.Url

	// Header contains the header fields and cookies
	// of incoming server request.
	Header() *specs.Header

	// Body specifies [io.Reader] of incoming server request.
	//
	// if request body not provided return nil.
	Body() io.Reader
}

Request is an interface for an HTTP request received by the Server.

type Response ΒΆ

type Response interface {
	// StatusCode specifies [specs.StatusCode] to be sent by the server in HTTP request.
	StatusCode() specs.StatusCode

	// Header contains the response header fields and cookies
	// to be sent by the server in HTTP response.
	Header() *specs.Header
}

Response is an interface for the HTTP response sent by the Server.

func BufferResponse ΒΆ

func BufferResponse(statusCode specs.StatusCode, contentType string, buffer []byte, configure ...func(Response)) Response

BufferResponse is implementation for the Response with []byte as response body to be sent by the Server.

Content type applies as "Content-Type" header value

if status code unspecified then specs.StatusCodeOK will be set if content type unspecified then specs.ContentTypeRaw will be set

func EmptyResponse ΒΆ

func EmptyResponse(statusCode specs.StatusCode, configure ...func(Response)) Response

EmptyResponse is implementation for the Response without body to be sent by the Server.

if status code unspecified then specs.StatusCodeOK will be set

func PermanentRedirectResponse ΒΆ

func PermanentRedirectResponse(url string, configure ...func(Response)) Response

PermanentRedirectResponse is implementation for the Response sent by the Server, based on EmptyResponse with specs.StatusCodePermanentRedirect and "Location" header provided by url.

func RedirectResponse ΒΆ

func RedirectResponse(url string, configure ...func(Response)) Response

RedirectResponse is implementation for the Response sent by the Server, based on EmptyResponse with specs.StatusCodeTemporaryRedirect and "Location" header provided by url.

func StreamResponse ΒΆ

func StreamResponse(statusCode specs.StatusCode, contentType string, stream io.Reader, contentLength int64, configure ...func(Response)) Response

StreamResponse is implementation for the Response that copy response body from io.Reader to be sent by the Server.

Content type applies as "Content-Type" header value

if status code unspecified then specs.StatusCodeOK will be set if content type unspecified then specs.ContentTypeRaw will be set

func TextResponse ΒΆ

func TextResponse(statusCode specs.StatusCode, contentType string, text string, configure ...func(Response)) Response

TextResponse is implementation for the Response with string as response body to be sent by the Server.

Content type applies as "Content-Type" header value

if status code unspecified then specs.StatusCodeOK will be set if content type unspecified then specs.ContentTypePlain will be set

type RoundTripper ΒΆ

type RoundTripper interface {
	// RoundTrip executes a single HTTP transaction,
	// returning a [ClientResponse] for the provided request parts.
	RoundTrip(ctx context.Context, method specs.HttpMethod, url *specs.Url, header *specs.Header, writer BodyWriter) (ClientResponse, error)
}

RoundTripper is an interface representing the ability to execute a single HTTP transaction, obtaining the ClientResponse for a given request parts specs.HttpMethod, specs.Url, specs.Header and optional BodyWriter.

A RoundTripper must be concurrent safe for use by multiple goroutines.

type RoundTripperFunc ΒΆ

type RoundTripperFunc func(ctx context.Context, method specs.HttpMethod, url *specs.Url, header *specs.Header, writer BodyWriter) (ClientResponse, error)

RoundTripperFunc shorthand implementation for RoundTripper

func (RoundTripperFunc) RoundTrip ΒΆ

func (f RoundTripperFunc) RoundTrip(ctx context.Context, method specs.HttpMethod, url *specs.Url, header *specs.Header, writer BodyWriter) (ClientResponse, error)

RoundTrip triggers top level function RoundTripperFunc

type Server ΒΆ

type Server struct {

	// Handler defines the function to be called for handling each incoming HTTP request.
	// This is the main handler implementing the [Handler] interface, which processes requests and generates responses.
	// Handler must be safe for concurrent use, as the server may invoke it from multiple goroutines simultaneously.
	//
	// If Handler is nil, the server cannot process requests and will panic during initialization.
	// If Handler implements the [ErrorHandler] interface and [Server.ErrorHandler] is nil,
	// it will be used as the ErrorHandler.
	Handler Handler

	// ErrorHandler defines a function for handling errors that occur during HTTP request processing.
	// This can include read/write errors, protocol errors, internal server errors, and other exceptional situations.
	//
	// ErrorHandler is called with error details and request context, allowing custom logic for logging,
	// returning special HTTP responses, or collecting metrics. Must be safe for concurrent use, as the server
	// may invoke it from multiple goroutines simultaneously.
	//
	// If ErrorHandler is not set, the server may use default error handling
	// or try to use the Handler as an ErrorHandler if it implements the [ErrorHandler] interface.
	ErrorHandler ErrorHandler

	// FilterConn handles all new incoming connections to provide filtering by address
	// Returns true - accept, false - close connection
	FilterConn func(addr net.Addr) bool

	// ServerName for sending in response headers.
	ServerName string

	// TLSHandshakeTimeout specifies the maximum amount of time to
	// wait for a TLS handshake. Zero means no timeout.
	TLSHandshakeTimeout time.Duration

	// TLSConfig optionally provides a TLS configuration
	TLSConfig *tls.Config

	// ReadTimeout is the maximum duration for server the entire
	// request, including the body. A zero or negative value means
	// there will be no timeout.
	ReadTimeout time.Duration

	// WriteTimeout is the maximum duration before timing out
	// writes of the response. A zero or negative value means
	// there will be no timeout.
	WriteTimeout time.Duration

	// IdleTimeout is the maximum amount of time to wait for the
	// next request when keep-alive are enabled.
	//
	// If zero, the value of ReadTimeout is used.
	// If negative, or if zero and ReadTimeout
	// is zero or negative, there is no timeout.
	IdleTimeout time.Duration

	// ReadLineMaxLength maximum size in bytes
	// to read lines in the request
	// such as headers and headlines
	//
	// If zero there is no limit
	ReadLineMaxLength int64

	// HeadMaxLength maximum size in bytes
	// to read lines in the request
	// such as headline and headers together
	//
	// If zero there is no limit
	HeadMaxLength int64

	// MaxBodySize maximum size in bytes
	// to read request body size.
	//
	// The server responds ErrTooLarge if this limit is greater than 0
	// and response body is greater than the limit.
	//
	// By default, request body size is unlimited.
	MaxBodySize int64

	// MaxEncodingSize maximum size in bytes
	// of the response body that will be encoded (based on the "Accept-Encoding" header)
	// when transfer by size - "Content-Length", except { "Transfer-Encoding": "chunked" }
	//
	// if not specified, the encoding will be skipped
	MaxEncodingSize int64

	// DisableKeepAlive controls whether HTTP keep-alive are enabled.
	//
	// Only very resource-constrained environments or servers in the process of
	// shutting down should disable them.
	//
	// By default, keep-alive are always enabled.
	DisableKeepAlive bool
	// contains filtered or unexported fields
}

A Server defines parameters for running an HTTP server. The zero value for Server is a valid configuration.

func DefaultServer ΒΆ

func DefaultServer(handler Handler) *Server

DefaultServer factory for creating Server with optimal parameters for perfomance and safety

Each call creates a new instance of Server with provided [Server.Handler] parameter

func (*Server) IsShutdown ΒΆ

func (srv *Server) IsShutdown() bool

IsShutdown checks if the server is shutting down or is already shut down after calling Server.Shutdown

func (*Server) ListenAndServe ΒΆ

func (srv *Server) ListenAndServe(addr string) error

ListenAndServe listens on the TCP network address and then calls Server.Serve to handle requests on incoming connections.

If addr is blank, ":http" is used.

ListenAndServe always returns a non-nil error. After Server.Shutdown, the returned error is specs.ErrClosed.

func (*Server) ListenAndServeTLS ΒΆ

func (srv *Server) ListenAndServeTLS(addr, certFile, keyFile string) error

ListenAndServeTLS listens on the TCP network address and then calls Server.ServeTLS to handle requests on incoming connections.

Filenames containing a certificate and matching private key for the server must be provided.

If addr is blank, ":http" is used.

ListenAndServeTLS always returns a non-nil error. After Server.Shutdown, the returned error is specs.ErrClosed.

func (*Server) ListenAndServeTLSRaw ΒΆ

func (srv *Server) ListenAndServeTLSRaw(addr string, cert tls.Certificate) error

ListenAndServeTLSRaw listens on the TCP network address and then calls Server.ServeTLSRaw to handle requests on incoming connections.

Certificate and matching private key for the server must be provided.

If addr is blank, ":http" is used.

ListenAndServeTLSRaw always returns a non-nil error. After Server.Shutdown, the returned error is specs.ErrClosed.

func (*Server) Serve ΒΆ

func (srv *Server) Serve(listener net.Listener) error

Serve accepts incoming connections on the net.Listener, creating a new service goroutine for each. The service goroutines read requests and then call [Server.Handler] to reply to them.

HTTP/2 not supported

Serve always returns a non-nil error. After Server.Shutdown, the returned error is specs.ErrClosed.

func (*Server) ServeTLS ΒΆ

func (srv *Server) ServeTLS(lst net.Listener, certFile, keyFile string) error

ServeTLS accepts incoming connections on the net.Listener, creating a new service goroutine for each. The service goroutines perform TLS setup and then read requests, calling [Server.Handler] to reply to them.

Filenames containing a certificate and matching private key for the server must be provided.

ServeTLS always returns a non-nil error. After Server.Shutdown, the returned error is specs.ErrClosed.

func (*Server) ServeTLSRaw ΒΆ

func (srv *Server) ServeTLSRaw(lst net.Listener, cert tls.Certificate) error

ServeTLSRaw accepts incoming connections on the net.Listener, creating a new service goroutine for each. The service goroutines perform TLS setup and then read requests, calling [Server.Handler] to reply to them.

Certificate and matching private key for the server must be provided.

ServeTLSRaw always returns a non-nil error. After Server.Shutdown, the returned error is specs.ErrClosed.

func (*Server) Shutdown ΒΆ

func (srv *Server) Shutdown()

Shutdown gracefully shuts down the server without interrupting any active connections. Shutdown works by first closing all open listeners, then closing all idle connections, and then waiting indefinitely for connections to return to idle and then shutdown. If the provided context expires before the shutdown is complete, Shutdown returns the context's error, otherwise it returns any error returned from closing the Server's underlying Listener(s).

When Shutdown is called, Server.Serve, Server.ListenAndServe, etc. immediately return [ErrServerClosed]. Make sure the program doesn't exit and waits instead for Shutdown to return.

Shutdown does not attempt to close nor wait for hijacked connections such as WebSockets. The caller of Shutdown should separately notify such long-lived connections of shutdown and wait for them to close.

Once Shutdown has been called on a server, it may not be reused; future calls to methods such as Serve will return ErrServerClosed.

func (*Server) TLSHasNextProto ΒΆ

func (srv *Server) TLSHasNextProto(proto string) bool

TLSHasNextProto checks if a handler function is specified for the upgraded protocol during a TLS connection when an ALPN protocol upgrade has occurred.

The proto is the protocol name negotiated.

The handle function can be specified using TLSNextProto

func (*Server) TLSNextProto ΒΆ

func (srv *Server) TLSNextProto(proto string, handler NextProtoHandler)

TLSNextProto specifies a function to take over ownership of the provided TLS connection when an ALPN protocol upgrade has occurred.

The proto is the protocol name negotiated.

NextProtoHandler argument should be used to handle HTTP requests. The connection is automatically closed when the function returns.

HTTP/2 support is not enabled automatically.

type TlsDialer ΒΆ

type TlsDialer interface {
	// Handshake connects to the address on the named network.
	Handshake(ctx context.Context, conn net.Conn, host string) (net.Conn, error)
}

TlsDialer is an interface representing the ability to dial tls connection and make Handshake.

type TlsDialerFunc ΒΆ

type TlsDialerFunc func(ctx context.Context, conn net.Conn, host string) (net.Conn, error)

TlsDialerFunc shorthand implementation for TlsDialer

func (TlsDialerFunc) Handshake ΒΆ

func (f TlsDialerFunc) Handshake(ctx context.Context, conn net.Conn, host string) (net.Conn, error)

Handshake triggers top level function TlsDialerFunc

type Transport ΒΆ

type Transport struct {

	// Dialer specifies the dialer for creating unencrypted TCP connections.
	// If Dialer is nil then the transport dials using package net
	Dialer Dialer

	// Proxy specifies a function to return a proxy for a given
	// Request. If the function returns a non-nil error, the
	// request is aborted with the provided error.
	//
	// The proxy type is determined by the URL scheme. "http",
	// "https", "socks5", and "socks5h" are supported. If the scheme is empty,
	// "http" is assumed.
	// "socks5" is treated the same as "socks5h".
	//
	// If the proxy specs.Url contains a username & password subcomponents,
	// the proxy request will pass the username and password
	// in a `Proxy-Authorization` header.
	//
	// If Proxy is nil or returns a nil *specs.Url, no proxy is used.
	Proxy func(url *specs.Url) (*specs.Url, error)

	// ProxyDialTimeout specifies the maximum amount of time to
	// wait for a Proxy establish connection.
	//
	// If zero there is no timeout.
	ProxyDialTimeout time.Duration

	// TLSDialer specifies an optional dial function for creating
	// TLS connections and gone handshake for non-proxied HTTPS requests.
	//
	// If TLSDialer is nil will be used [tls.Client].
	//
	// If TLSDialer is set, it is assumed
	// that the returned net.Conn has already gone through the TLS handshake.
	TLSDialer TlsDialer

	// TLSClientConfig specifies the TLS configuration
	// to use with tls.Client.
	//
	// If nil, the default configuration is used.
	// If non-nil, HTTP/2 support may not be enabled by default.
	TLSConfig *tls.Config

	// TLSHandshakeTimeout specifies the maximum amount of time to
	// wait for a TLS handshake. Zero means no timeout.
	TLSHandshakeTimeout time.Duration

	// ReadTimeout is the maximum duration for server the entire
	// response, including the body. A zero or negative value means
	// there will be no timeout.
	ReadTimeout time.Duration

	// WriteTimeout is the maximum duration before timing out
	// writes of the request. A zero or negative value means
	// there will be no timeout.
	WriteTimeout time.Duration

	// ReadLineMaxLength maximum size in bytes
	// to read lines in the response
	// such as headers and headlines
	//
	// The client returns specs.ErrTooLarge if this limit is greater than 0
	// and response lines is greater than the limit.
	//
	// If zero there is no limit
	ReadLineMaxLength int64

	// HeadMaxLength maximum size in bytes
	// to read headline and headers together
	//
	// The client returns specs.ErrTooLarge if this limit is greater than 0
	// and response header size is greater than the limit.
	//
	// If zero there is no limit
	HeadMaxLength int64

	// MaxBodySize maximum size in bytes
	// to read response body size.
	//
	// The client returns specs.ErrTooLarge if this limit is greater than 0
	// and response body is greater than the limit.
	//
	// By default, response body size is unlimited.
	MaxBodySize int64
	// contains filtered or unexported fields
}

Transport is an implementation of RoundTripper that supports HTTP, HTTPS, and proxies like 'http', 'https', 'socks5' 'socks5h' (can be provided by Proxy).

Transport is a low-level primitive for making HTTP and HTTPS requests. For high-level functionality, such as cookies and redirects, see Client.

func DefaultTransport ΒΆ

func DefaultTransport() *Transport

DefaultTransport factory for creating Transport with optimal parameters for perfomance and safety

Each call creates a new instance of Transport

func (*Transport) RoundTrip ΒΆ

func (transport *Transport) RoundTrip(ctx context.Context, method specs.HttpMethod, url *specs.Url, header *specs.Header, writer BodyWriter) (ClientResponse, error)

RoundTrip implements the RoundTripper interface.

type TransportHijacker ΒΆ

type TransportHijacker struct {
	// Conn intercepted connection from Transport
	//
	// Can be nil if connection not stored
	Conn net.Conn
}

TransportHijacker container for store intercepted Transport connection.

Creates only by WithTransportHijacker

func WithTransportHijacker ΒΆ

func WithTransportHijacker(ctx context.Context) (*TransportHijacker, context.Context)

WithTransportHijacker returns a copy of context.Context in which the stored TransportHijacker.

If hijacker stored Transport will not do anything else with the connection when HTTP transaction ends. If ClientResponse has Body and you close it, it will also close net.Conn, keep this in mind.

Used only with Transport or Client for intercept connection.

Directories ΒΆ

Path Synopsis
mux
prm

Jump to

Keyboard shortcuts

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