engine

package
v1.3.1 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: MIT Imports: 35 Imported by: 1 module, 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

Package engine sends the requests of the HTTP client and captures everything about the response (SPEC §10.33 "The engine").

Prepare builds a request from the model of package format and the variables of package variables: the URL with its parameters, the headers (those a collection and its folders pass down, then the request's), the authorization and the body of every kind of the SPEC. Send does Prepare and then sends: it follows or keeps the redirects, answers a Digest challenge, keeps the cookies of the environment in a jar kept in the state, decodes gzip and deflate, takes the timings from net/http/httptrace, and keeps the body in memory up to a limit (50 MiB) and in a file of the cache beyond it. The context cancels a request at any moment.

Nothing here knows a user interface, and nothing reads the user's configuration: everything comes in through Config and Input. Only the standard library is used.

Index

Constants

View Source
const (
	// DefaultTimeoutMs is the timeout of a request (httpClient.timeoutMs).
	DefaultTimeoutMs = 30000
	// DefaultMaxRedirects is the number of redirects that are followed.
	DefaultMaxRedirects = 10
	// DefaultMemoryLimit is the size of a response body that is kept in memory; a larger one goes to a file of the cache.
	DefaultMemoryLimit = 50 << 20
)

The defaults of the settings (SPEC §10.33 "The engine").

View Source
const (
	HopRedirect = "redirect"
	HopDigest   = "digest"
)

The reasons a Hop went on.

View Source
const CookieStateKey = "httpclient.cookies"

CookieStateKey is the key of the cookies in the state of the workspace.

Variables

This section is empty.

Functions

This section is empty.

Types

type Body

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

Body is the body of a response: in memory when it fits the limit, otherwise in a file of the cache that is read in pages.

func NewMemoryBody

func NewMemoryBody(data []byte) *Body

NewMemoryBody makes the body of a response from bytes that are in memory, for a caller that builds a Response itself (a test of the response pane, a stored example).

func (*Body) Bytes

func (b *Body) Bytes() ([]byte, error)

Bytes returns the whole body (reading the file if there is one). A body that is in memory is returned without a copy: do not change it.

func (*Body) InMemory

func (b *Body) InMemory() bool

InMemory says that the body is in memory, not in a file.

func (*Body) Open

func (b *Body) Open() (io.ReadCloser, error)

Open returns a reader of the whole body.

func (*Body) Path

func (b *Body) Path() string

Path is the cache file of a body that did not fit the memory limit, and empty otherwise.

func (*Body) ReadAt

func (b *Body) ReadAt(p []byte, off int64) (int, error)

ReadAt reads len(p) bytes at the offset; it is io.ReaderAt, for the pages of the response pane.

func (*Body) Remove

func (b *Body) Remove() error

Remove deletes the cache file of the body, if there is one. The body cannot be read afterwards.

func (*Body) Size

func (b *Body) Size() int64

Size is the number of bytes of the body.

type ClientCert

type ClientCert struct {
	// Host is a pattern for the host name ("api.example.com", "*.example.com"); a pattern with a colon matches host:port.
	Host     string
	CertFile string
	KeyFile  string
	// Passphrase decrypts a key in the legacy PEM encryption (the caller reads it from the keyring).
	Passphrase string
}

ClientCert is a client certificate for the hosts that match Host (httpClient.clientCertificates).

type Config

type Config struct {
	// TimeoutMs limits a request, its body included; 0 is DefaultTimeoutMs and a negative number is no limit.
	TimeoutMs int
	// FollowRedirects is whether redirects are followed (nil: yes). MaxRedirects limits them (0: DefaultMaxRedirects).
	FollowRedirects *bool
	MaxRedirects    int
	// VerifyTLS is whether certificates are verified (nil: yes).
	VerifyTLS *bool
	// CAFile is a PEM file of certificate authorities that are trusted in addition to the system's.
	CAFile string
	// ClientCerts are the client certificates, the first match wins.
	ClientCerts []ClientCert
	// Proxy is the URL of the proxy (httpClient.proxy); empty: HTTP_PROXY, HTTPS_PROXY and NO_PROXY.
	Proxy string
	// UserAgent is sent unless the request has the header; empty: "Emetos/dev".
	UserAgent string
	// CacheDir holds the bodies that do not fit the memory; it is created when needed.
	CacheDir string
	// MemoryLimit is the largest body kept in memory (0: DefaultMemoryLimit).
	MemoryLimit int64
	// Jars keeps the cookies (nil: they live as long as the engine).
	Jars *Jars
}

Config is what the engine takes from the settings of the editor. The zero value is the default of every setting.

type Engine

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

Engine sends requests. It is safe for concurrent use; Close it when it is no longer needed.

func New

func New(cfg Config) *Engine

New makes an engine. The files of the configuration (the CA file, the certificates) are read when a request first needs them.

func (*Engine) Close

func (e *Engine) Close()

Close closes the idle connections.

func (*Engine) Do

func (e *Engine) Do(ctx context.Context, p *Prepared) (*Response, error)

Do sends a prepared request.

func (*Engine) Jars

func (e *Engine) Jars() *Jars

Jars returns the cookie jars of the engine.

func (*Engine) Prepare

func (e *Engine) Prepare(in Input) (*Prepared, error)

Prepare builds the request: variables, URL with its parameters, headers, authorization and body.

func (*Engine) Send

func (e *Engine) Send(ctx context.Context, in Input) (*Response, error)

Send builds the request (Prepare) and sends it. The context cancels it, even while the body is being read.

When the redirects exceed the limit, the response of the last one is returned with its chain together with the error EngineTooManyRedirects; for every other failure the response is nil.

type Hop

type Hop struct {
	Method     string
	URL        string
	StatusCode int
	Status     string
	Header     http.Header
	Timings    Timings
	// Reason is HopRedirect or HopDigest: why the request went on.
	Reason string
}

Hop is a response that came before the final one: a redirect that was followed, or the Digest challenge that was answered.

type Input

type Input struct {
	// Request is the request as the file has it, with its {{variables}}.
	Request format.Request
	// Headers are the headers the collection and its folders pass down, outermost first; a header of the request with the same
	// name replaces them.
	Headers []format.Pair
	// Auth is the authorization that applies (the caller resolved "inherit" along the folders); nil: the request's own.
	Auth *format.Auth
	// Resolver replaces the variables; nil: the text is sent as written.
	Resolver *variables.Resolver
	// Folder is the workspace folder, which every file stays inside; Dir is the folder of the request file, where the body
	// files are (empty: Folder).
	Folder string
	Dir    string
	// Texts are the texts of body files by name, used in place of reading the files: the request tab sends what is in its boxes, which
	// may not be saved. A name that is not in Texts is read from Dir as before.
	Texts map[string]string
	// Environment names the cookie jar (empty: the jar of requests without an environment).
	Environment string
	// OAuth is the access token an authorization of type oauth2 sends; the caller got it (and refreshed it) before sending. Without it
	// such a request fails with EngineOAuthTokenMissing.
	OAuth *OAuthToken
}

Input is a request to send: the model, and what it needs from outside.

type Jar

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

Jar is the cookie jar of one environment. It is safe for concurrent use.

func (*Jar) Cookies

func (j *Jar) Cookies(u *url.URL) []*http.Cookie

Cookies implements http.CookieJar.

func (*Jar) Delete

func (j *Jar) Delete(domain string)

Delete removes the cookies of a domain (and of its subdomains, which a cookie set for the domain reaches); an empty domain removes every cookie.

func (*Jar) List

func (j *Jar) List() []StoredCookie

List returns the cookies that have not expired, sorted by domain, path and name.

func (*Jar) SetCookies

func (j *Jar) SetCookies(u *url.URL, cookies []*http.Cookie)

SetCookies implements http.CookieJar.

type Jars

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

Jars keeps one cookie jar per environment ("" is the jar of requests sent without an environment), in the state of the workspace (SPEC §10.33 "The engine"). A jar is an http.CookieJar that remembers what it was given, because net/http/cookiejar cannot be listed or written out.

func NewJars

func NewJars(state State) *Jars

NewJars makes the jars, kept in state (nil: the cookies live as long as the Jars).

func (*Jars) Jar

func (j *Jars) Jar(env string) *Jar

Jar returns the jar of the environment, loading it from the state the first time.

func (*Jars) Save

func (j *Jars) Save(env string) error

Save writes the jar of the environment to the state if it changed since it was loaded or saved.

type OAuthToken

type OAuthToken struct {
	// Value is the access token.
	Value string
	// Scheme is the word before it in the Authorization header; "Bearer" when empty.
	Scheme string
}

OAuthToken is an access token to send with a request (OAuth 2.0, SPEC §10.33).

type Prepared

type Prepared struct {
	// Method and URL are what will be sent (the URL has the parameters and an API key in the query).
	Method string
	URL    *url.URL
	// Header holds the headers before the engine adds its own (User-Agent, Accept-Encoding, Content-Length).
	Header http.Header
	// Host overrides the Host header when the request set one.
	Host string
	// Unresolved and MissingSecrets are the variables that had no value.
	Unresolved     []string
	MissingSecrets []string
	// contains filtered or unexported fields
}

Prepared is a request that is ready to send.

type Response

type Response struct {
	// Status is the status line without the protocol ("200 OK"), StatusCode its number.
	Status     string
	StatusCode int
	Proto      string
	Header     http.Header
	// Cookies are those the final response set.
	Cookies []*http.Cookie
	// Body is the body after Content-Encoding was decoded.
	Body *Body
	// Transferred is the number of bytes the body had on the wire (before decoding).
	Transferred int64
	// Decoded lists the encodings that were removed ("gzip", "deflate"), outermost first.
	Decoded []string
	// URL is the URL of the final exchange.
	URL string
	// Chain holds the responses before the final one, in order.
	Chain []Hop
	// Request is the request of the final exchange.
	Request Sent
	// Timings are those of the final exchange; Total is the whole of Send, chain included.
	Timings Timings
	// TLS is nil for a plain http exchange.
	TLS *TLSInfo
	// InsecureTLS says that the certificate was not verified.
	InsecureTLS bool
	// Unresolved and MissingSecrets are the variables the request used that had no value (they were sent as written).
	Unresolved     []string
	MissingSecrets []string
	// Warnings are problems that did not stop the request (the cookies could not be saved).
	Warnings []string
}

Response is everything about a finished request.

type Sent

type Sent struct {
	Method string
	URL    string
	Header http.Header
	// BodySize is the length of the body when it is known, and -1 when it was streamed.
	BodySize int64
}

Sent describes the request as it was sent in the last exchange (with the authorization in its headers, so a caller that shows or stores it masks them).

type State

type State interface {
	Get(key string) (json.RawMessage, bool)
	Set(key string, value any) error
}

State is the part of extension.State the cookies use (the same as variables.State).

type StoredCookie

type StoredCookie struct {
	Name  string `json:"name"`
	Value string `json:"value"`
	// Domain is the host the cookie belongs to, without a leading dot.
	Domain string `json:"domain"`
	// HostOnly says that only Domain itself gets the cookie, not its subdomains.
	HostOnly bool   `json:"hostOnly,omitempty"`
	Path     string `json:"path"`
	// Expires is the zero time for a session cookie.
	Expires  time.Time `json:"expires,omitzero"`
	Secure   bool      `json:"secure,omitempty"`
	HTTPOnly bool      `json:"httpOnly,omitempty"`
}

StoredCookie is a cookie as the jar keeps it and as the state stores it.

type TLSInfo

type TLSInfo struct {
	Version     string
	CipherSuite string
	ServerName  string
	Subject     string
	Issuer      string
	NotAfter    time.Time
}

TLSInfo describes the TLS connection of the final exchange.

type Timings

type Timings struct {
	// DNS is the lookup of the host name.
	DNS time.Duration
	// Connect is the TCP connection.
	Connect time.Duration
	// TLS is the TLS handshake.
	TLS time.Duration
	// Sent is the time to write the request, from the moment the connection was ready.
	Sent time.Duration
	// FirstByte is the wait between the end of the request and the first byte of the response.
	FirstByte time.Duration
	// Download is the time from the first byte to the end of the body (zero for a response that was not read to its end).
	Download time.Duration
	// Total is the whole exchange.
	Total time.Duration
	// Reused says that the connection was already open.
	Reused bool
}

Timings are the phases of one exchange (SPEC §10.33 "The engine"). A phase that did not happen (the DNS lookup of an IP address, the connection of a reused one, TLS of http) is zero.

Jump to

Keyboard shortcuts

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