Skip to main content

Request

Struct Request 

Source
pub struct Request { /* private fields */ }
Expand description

A request under construction. Created with Request::new, one of the free functions (get, post, …) or a Client, and sent with Request::send or Request::send_to.

Builder methods that can fail (header) record the error and return it from send, so that a request can be built in one expression.

let response = curlite::post("https://example.com/api?debug=1")
    .header("Authorization", "Bearer secret")
    .form([("name", "value")])
    .send()?;
assert!(response.status().is_success());

Implementations§

Source§

impl Request

Source

pub fn new(method: Method, url: &str) -> Self

Starts a request. url may contain a query string, which is kept; a fragment is dropped. The URL is parsed by libcurl when the request is sent.

Source

pub fn header<N, V>(self, name: N, value: V) -> Self

Sets a header, replacing any previous value with the same name.

Header values must be visible ASCII. Pass a HeaderValue built with HeaderValue::from_bytes for opaque octets.

Source

pub fn headers(self, headers: HeaderMap) -> Self

Replaces all headers.

Source

pub fn query(self, name: &str, value: &str) -> Self

Appends a query parameter. Name and value are percent-encoded. A pair with an empty value is serialized as just its name.

Source

pub fn body(self, content_type: Mime, data: impl Into<Bytes>) -> Self

Sends data as the body with the given Content-Type, unless a Content-Type header was set explicitly. The data is not copied.

Source

pub fn body_reader( self, content_type: Mime, reader: impl Read + Seek + 'static, ) -> Self

Streams the body from reader with the given Content-Type, unless a Content-Type header was set explicitly. Nothing is buffered beyond libcurl’s upload chunk.

The reader has to seek: its length is taken from seeking to the end, and it is rewound for 307/308 redirects and for retries on a connection the server closed. For in-memory data use Request::body, which does not copy.

Source

pub fn json<T: Serialize + ?Sized>(self, value: &T) -> Self

Sends value serialized as JSON with application/json, unless a Content-Type header was set explicitly. A serialization error is returned from send.

Source

pub fn form<'a>( self, pairs: impl IntoIterator<Item = (&'a str, &'a str)>, ) -> Self

Sends pairs as an application/x-www-form-urlencoded body.

Source

pub fn multipart(self, multipart: Multipart) -> Self

Sends a multipart/form-data body.

Source

pub fn timeout(self, timeout: Duration) -> Self

Time limit for one transfer, each redirect hop counting separately. Default none: a transfer that keeps moving may take as long as it needs, one that stops moving is caught by Request::stall_timeout. Zero means no limit.

Source

pub fn connect_timeout(self, timeout: Duration) -> Self

Time limit for establishing the connection, including the TLS handshake, default 30 seconds. Zero restores libcurl’s default of 300 seconds.

Source

pub fn stall_timeout(self, timeout: Duration) -> Self

Aborts the transfer once no data has moved in either direction for this long, default 30 seconds. Unlike Request::timeout it does not punish a large download for being large. Rounded up to whole seconds; zero disables the check. A stalled transfer fails with Error::Curl and is_operation_timedout().

Time a send_reader spends waiting for its consumer does not count: libcurl only runs while the reader is read.

Source

pub fn follow_redirects(self, follow: bool) -> Self

Whether to follow 3xx redirects, default true. When disabled, the redirect response itself is returned.

Redirects are followed by this crate, not by libcurl: 303 turns any method into GET, 301 and 302 turn POST into GET, 307 and 308 resend the body with the same method. Only http and https targets are followed, anything else is Error::UnsupportedScheme. Authorization, Cookie and Request::auth credentials are dropped when the redirect leaves the origin (scheme, host and port); other headers, such as an API key of your own, travel with the request, as do proxy, Unix socket and client certificate settings, like in curl.

Source

pub fn max_redirects(self, max: u32) -> Self

Maximum number of redirects to follow before failing with Error::TooManyRedirects, default 10.

Source

pub fn http_version(self, version: HttpVersion) -> Self

The HTTP version to use. By default libcurl decides: HTTP/2 over TLS when it was built with HTTP/2 and the server offers it, HTTP/1.1 otherwise.

Source

pub fn proxy(self, proxy: impl Into<String>) -> Self

Sends the request through proxy, such as http://proxy:3128 or socks5h://localhost:1080. Without this, libcurl honours the http_proxy, https_proxy, all_proxy and no_proxy environment variables.

Source

pub fn unix_socket(self, path: impl Into<PathBuf>) -> Self

Connects to a Unix domain socket instead of the URL’s host, which is still sent as Host. For Docker, systemd and similar local APIs.

Source

pub fn ca_bundle(self, path: impl Into<PathBuf>) -> Self

A PEM file with the CA certificates to trust, instead of the system store.

Without this, on a libcurl built on OpenSSL with a hashed certificate directory (/etc/ssl/certs/<hash>.0, as Debian, Ubuntu, Alpine and Arch ship it), curlite lets OpenSSL look the needed CA certificates up by hash instead of parsing the whole bundle, which saves about 20 ms of CPU per process on x86 and more on small devices. Setting a bundle turns that off.

Source

pub fn danger_accept_invalid_certs(self) -> Self

Skips TLS certificate and host name verification. For development against self-signed certificates only.

Source

pub fn compression(self, enabled: bool) -> Self

Whether to ask for compressed responses (Accept-Encoding with every encoding this libcurl can decode) and decode them transparently, default true. Off, the raw body is returned.

Source

pub fn auth(self, auth: Auth) -> Self

Authenticates with the given method. Credentials are dropped, like an Authorization header, when a redirect leaves the origin.

Source

pub fn basic_auth( self, user: impl Into<String>, password: impl Into<String>, ) -> Self

Source

pub fn bearer_auth(self, token: impl Into<String>) -> Self

Source

pub fn netrc(self) -> Self

Takes credentials for the host from ~/.netrc when the request has none, like curl --netrc-optional. Looked up per host, so they survive redirects.

Source

pub fn proxy_auth(self, auth: Auth) -> Self

Authenticates with the proxy, for the corporate proxies that want NTLM or Kerberos: Basic, Digest, Ntlm and Negotiate through libcurl’s proxy authentication. Bearer is not a proxy scheme and fails at send. Kept across redirects, since it is for the proxy, not the origin.

Source

pub fn client_cert( self, cert: impl Into<PathBuf>, key: impl Into<PathBuf>, ) -> Self

Authenticates the TLS connection with a client certificate: PEM files with the certificate and the private key, which may be the same file. On Windows, libcurl’s Schannel backend does not read PEM files; it wants a certificate from the system store or a PKCS#12 file, so there a static-curl build with OpenSSL or rustls is the way to use this.

Source

pub fn max_body_size(self, limit: Option<u64>) -> Self

Upper bound for a body that Request::send holds in memory, default 64 MiB. A larger Content-Length fails before the body is read, a body that grows past the bound fails as it arrives, both with Error::BodyTooLarge. None removes the bound. Request::send_to and Request::send_reader are not bounded.

Source

pub fn on_progress(self, f: impl FnMut(Progress) + 'static) -> Self

Reports transfer progress. f runs between libcurl’s steps whenever the byte counts change and once more when the transfer ends, never inside a libcurl callback, so it may block or send requests of its own. The counts are per transfer: a redirect that is followed starts them over.

Source

pub fn send(self) -> Result<Response>

Performs the request and reads the whole response into memory.

Requests on the same thread share one connection cache, so calls to the same host reuse the connection.

Source

pub fn send_to(self, writer: &mut dyn Write) -> Result<Response>

Performs the request and writes the response body to writer as it arrives, instead of holding it in memory. The returned response has an empty body. Bodies of redirects that are followed are discarded.

The writer runs between libcurl’s steps, never inside its callbacks, so it may send requests of its own.

Source

pub fn send_reader(self) -> Result<ResponseReader>

Performs the request up to the response headers and returns the body as a reader that pulls from the connection on demand, with backpressure.

Source

pub fn url(&self) -> &str

The URL the request will be sent to, including query parameters.

Source§

impl Request

Source

pub fn to_curl(&self) -> String

The request as a curl command line, for logs, bug reports and trying things by hand.

Everything that reaches the wire is in it: method, URL, headers, the body, redirect handling, HTTP version, proxy, Unix socket, CA bundle, certificate verification and compression. Timeouts are not; they do not change the request. One difference remains: with -L, curl keeps a verb such as DELETE across redirects where this crate switches to GET as RFC 9110 says. Text bodies and fields up to 64 KiB are quoted inline, binary or larger ones and streamed bodies become @- (standard input) with a note in a trailing comment. Header names are lowercase, as http stores them. Values are single-quoted for a POSIX shell, one option per line.

Credentials are not printed. Passwords, bearer tokens, credentials in the URL and the values of Authorization, Proxy-Authorization and Cookie headers appear as shell variables (-u "user:$PASSWORD", --oauth2-bearer "$TOKEN", -H "cookie: $COOKIE"), so the output runs once the variable is exported. Anything else, including a key in the query string or a header of your own, is printed as it is.

let request = curlite::post("https://example.com/api?v=1")
    .basic_auth("alice", "secret")
    .header("User-Agent", "tool/1.0")
    .form([("name", "a b")]);
assert_eq!(
    request.to_curl(),
    "curl 'https://example.com/api?v=1' \\\n  \
       -u \"alice:$PASSWORD\" \\\n  \
       -H 'user-agent: tool/1.0' \\\n  \
       --data 'name=a+b' \\\n  \
       -L --max-redirs 10 \\\n  \
       --compressed"
);

Trait Implementations§

Source§

impl Debug for Request

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.