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
impl Request
Sourcepub fn new(method: Method, url: &str) -> Self
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.
Sourcepub fn header<N, V>(self, name: N, value: V) -> Selfwhere
N: TryInto<HeaderName>,
N::Error: Into<Error>,
V: TryInto<HeaderValue>,
V::Error: Into<Error>,
pub fn header<N, V>(self, name: N, value: V) -> Selfwhere
N: TryInto<HeaderName>,
N::Error: Into<Error>,
V: TryInto<HeaderValue>,
V::Error: Into<Error>,
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.
Sourcepub fn query(self, name: &str, value: &str) -> Self
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.
Sourcepub fn body(self, content_type: Mime, data: impl Into<Bytes>) -> Self
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.
Sourcepub fn body_reader(
self,
content_type: Mime,
reader: impl Read + Seek + 'static,
) -> Self
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.
Sourcepub fn json<T: Serialize + ?Sized>(self, value: &T) -> Self
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.
Sourcepub fn form<'a>(
self,
pairs: impl IntoIterator<Item = (&'a str, &'a str)>,
) -> Self
pub fn form<'a>( self, pairs: impl IntoIterator<Item = (&'a str, &'a str)>, ) -> Self
Sends pairs as an application/x-www-form-urlencoded body.
Sourcepub fn timeout(self, timeout: Duration) -> Self
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.
Sourcepub fn connect_timeout(self, timeout: Duration) -> Self
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.
Sourcepub fn stall_timeout(self, timeout: Duration) -> Self
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.
Sourcepub fn follow_redirects(self, follow: bool) -> Self
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.
Sourcepub fn max_redirects(self, max: u32) -> Self
pub fn max_redirects(self, max: u32) -> Self
Maximum number of redirects to follow before failing with
Error::TooManyRedirects, default 10.
Sourcepub fn http_version(self, version: HttpVersion) -> Self
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.
Sourcepub fn proxy(self, proxy: impl Into<String>) -> Self
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.
Sourcepub fn unix_socket(self, path: impl Into<PathBuf>) -> Self
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.
Sourcepub fn ca_bundle(self, path: impl Into<PathBuf>) -> Self
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.
Sourcepub fn danger_accept_invalid_certs(self) -> Self
pub fn danger_accept_invalid_certs(self) -> Self
Skips TLS certificate and host name verification. For development against self-signed certificates only.
Sourcepub fn compression(self, enabled: bool) -> Self
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.
Sourcepub fn auth(self, auth: Auth) -> Self
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.
Sourcepub fn bearer_auth(self, token: impl Into<String>) -> Self
pub fn bearer_auth(self, token: impl Into<String>) -> Self
Sourcepub fn netrc(self) -> Self
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.
Sourcepub fn proxy_auth(self, auth: Auth) -> Self
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.
Sourcepub fn client_cert(
self,
cert: impl Into<PathBuf>,
key: impl Into<PathBuf>,
) -> Self
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.
Sourcepub fn max_body_size(self, limit: Option<u64>) -> Self
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.
Sourcepub fn on_progress(self, f: impl FnMut(Progress) + 'static) -> Self
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.
Sourcepub fn send(self) -> Result<Response>
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.
Sourcepub fn send_to(self, writer: &mut dyn Write) -> Result<Response>
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.
Sourcepub fn send_reader(self) -> Result<ResponseReader>
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§impl Request
impl Request
Sourcepub fn to_curl(&self) -> String
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"
);