Skip to main content

RequestHead

Struct RequestHead 

Source
pub struct RequestHead<'a> { /* private fields */ }
Expand description

A parsed request head, borrowed from the connection’s buffer.

Every accessor is a slice of the bytes that arrived; nothing is copied. The view stays valid until the next call that mutates the connection. Read it again later with ServerConn::request.

§Examples

use http_net::{Method, ServerConn, ServerEvent, Version};

let mut conn = ServerConn::new();
let _ = conn.feed(b"GET /search?q=rust HTTP/1.1\r\nHost: example.com\r\n\r\n");
let ServerEvent::Request(req) = conn.poll().unwrap() else { panic!() };
assert_eq!(req.method(), Method::Get);
assert_eq!(req.path(), "/search");
assert_eq!(req.query(), Some("q=rust"));
assert_eq!(req.version(), Version::Http11);
assert_eq!(req.host(), Some("example.com"));
assert!(req.keep_alive());

Implementations§

Source§

impl<'a> RequestHead<'a>

Source

pub fn method(&self) -> Method

The method, classified.

§Examples
assert_eq!(req.method(), Method::Delete);
Source

pub fn method_str(&self) -> &'a str

The method exactly as received.

§Examples
assert_eq!(req.method(), Method::Other);
assert_eq!(req.method_str(), "PROPFIND");
Source

pub fn target(&self) -> &'a str

The request target exactly as received (origin form /path?query, absolute form, authority form for CONNECT, or *).

§Examples
assert_eq!(req.target(), "/a%20b?x=1");
Source

pub fn target_form(&self) -> TargetForm

Which of the four RFC 9112 section 3.2 forms the target uses.

§Examples
assert_eq!(req.target_form(), TargetForm::Absolute);
Source

pub fn path(&self) -> &'a str

The path: the target up to (not including) the first ?, with percent-encoding left as received.

For an absolute-form target (http://host/p?q) this is the path after the authority (/p), and / when that path is empty, so a router sees the same path whichever form the client used. For * and for CONNECT’s authority form it is the whole target.

§Examples
assert_eq!(req.path(), "/files/a.txt");

assert_eq!(req.path(), "/files/b.txt");
Source

pub fn query(&self) -> Option<&'a str>

The query after the first ?, if there is one.

§Examples
assert_eq!(req.query(), None);
Source

pub fn version(&self) -> Version

The protocol version.

§Examples
assert_eq!(req.version(), Version::Http10);
Source

pub fn headers(&self) -> Headers<'a> ⓘ

All fields in arrival order.

§Examples
assert_eq!(req.headers().len(), 2);
Source

pub fn header(&self, name: &str) -> Option<&'a [u8]>

The value of the first field named name (ASCII case-insensitive).

§Examples
assert_eq!(req.header("accept"), Some(&b"text/html"[..]));
assert_eq!(req.header("cookie"), None);
Source

pub fn header_str(&self, name: &str) -> Option<&'a str>

Like header, but only when the value is UTF-8.

§Examples
assert_eq!(req.header_str("host"), Some("a"));
assert_eq!(req.header_str("x"), None);
Source

pub fn header_all<'n>(&self, name: &'n str) -> HeaderValues<'a, 'n> ⓘ

The values of every field named name (ASCII case-insensitive), in arrival order: for fields that may be repeated, such as via, forwarded, or cookie from clients that send one line per cookie.

§Examples
let cookies: Vec<&[u8]> = req.header_all("cookie").collect();
assert_eq!(cookies, [&b"a=1"[..], &b"b=2"[..]]);
assert_eq!(req.header_all("accept").count(), 0);

// The values borrow the head, not the name.
let first = {
    let name = String::from("COOKIE");
    req.header_all(&name).next()
};
assert_eq!(first, Some(&b"a=1"[..]));
Source

pub fn content_length(&self) -> Option<u64>

The declared Content-Length, if the request has one. Unlike framing, which reports Content-Length: 0 as BodyFraming::None, this tells Some(0) from an absent field.

§Examples
assert_eq!(req.framing(), BodyFraming::None);
assert_eq!(req.content_length(), Some(0));
Source

pub fn host(&self) -> Option<&'a str>

The authority the request is for (host [":" port]), if known.

This is the Host field, except for an absolute-form target (GET http://example.com/ HTTP/1.1), whose authority wins: RFC 9112 section 3.2.2 requires a server to ignore Host then, so the two can never be read differently. The raw field stays available through header("host"). HTTP/1.1 requests always carry a valid Host; HTTP/1.0 requests may not, and an empty Host (a target with no authority) is reported as Some("").

§Examples
assert_eq!(req.host(), Some("127.0.0.1:8080"));

assert_eq!(req.host(), Some("a.test"));
assert_eq!(req.header("host"), Some(&b"b.test"[..]));
Source

pub fn expects_continue(&self) -> bool

Whether the client sent Expect: 100-continue and is waiting for a 100 Continue before sending the body. Only HTTP/1.1 requests that have a body report it (RFC 9110 section 10.1.1).

Answer it before reading the body: either ServerConn::send_continue, or a final response straight away (which closes the connection afterwards, since the body was not read). The blocking Server sends 100 Continue itself.

§Examples
assert!(req.expects_continue());
Source

pub fn framing(&self) -> BodyFraming

How the request body is delimited.

§Examples
assert_eq!(req.framing(), BodyFraming::Chunked);
Source

pub fn keep_alive(&self) -> bool

Whether the client allows the connection to stay open after this exchange (HTTP/1.1 unless Connection: close; HTTP/1.0 only with Connection: keep-alive).

§Examples
assert!(!req.keep_alive());
Source

pub fn is_upgrade(&self) -> bool

Whether this is an HTTP/1.1 request to switch protocols: Connection lists upgrade and an Upgrade field offers at least one protocol other than h2c (read the offers with upgrade_protocols). Answer with Response::switching_protocols naming an offered protocol to hand the connection over.

h2c is never an offer: RFC 9113 section 3.1 deprecates the HTTP/2 upgrade, and a proxy that forwards it blindly is open to h2c smuggling. A request offering only h2c is served as HTTP/1.1.

§Examples
assert!(req.is_upgrade());
assert_eq!(req.header("upgrade"), Some(&b"websocket"[..]));

assert!(!req.is_upgrade());
Source

pub fn has_unknown_expectation(&self) -> bool

Whether the request carries an expectation other than 100-continue (any Expect list element, any HTTP version), which a server may answer with 417 Expectation Failed (RFC 9110 section 10.1.1). The core never answers it by itself; the blocking server does. The expectation never changes how the body is framed.

§Examples
assert!(req.expects_continue());
assert!(req.has_unknown_expectation());
Source

pub fn upgrade_protocols(&self) -> ListElements<'a, 'static> ⓘ

The protocols the request’s Upgrade field offers, in order, as product tokens (websocket, foo/2), across every Upgrade line; h2c is left out (it is never an offer). Empty unless is_upgrade.

§Examples
let offered: Vec<&[u8]> = req.upgrade_protocols().collect();
assert_eq!(offered, [&b"websocket/13"[..], b"irc"]);
Source

pub fn connection_options(&self) -> ListElements<'a, 'static> ⓘ

The options the request’s Connection field lists, across every Connection line, in order (close, keep-alive, upgrade, and the names of fields that are hop-by-hop for this message). Compare them ASCII case-insensitively. A proxy passes them to is_hop_by_hop.

§Examples
let options: Vec<&[u8]> = req.connection_options().collect();
assert_eq!(options, [&b"keep-alive"[..], b"X-Trace"]);
Source

pub fn header_list<'n>(&self, name: &'n str) -> ListElements<'a, 'n> ⓘ

The elements of a comma-separated list field (#rule, RFC 9110 section 5.6.1) across every line with this name, in order, trimmed of whitespace, empty elements skipped. A comma inside a quoted string does not split an element.

§Examples
let accept: Vec<&[u8]> = req.header_list("accept").collect();
assert_eq!(accept, [&b"text/html"[..], b"x/y;q=\"0.5,1\""]);
Source§

impl<'a> RequestHead<'a>

Source

pub fn raw(&self) -> RawHead<'a>

The head’s bytes and the spans of its parts, for code that works on offsets (passports, proxies, other engines).

§Examples

See RawHead.

Source

pub fn copy_into( &self, bytes: &mut Vec<u8>, fields: &mut Vec<FieldSpan>, ) -> Result<HeadFacts, HttpError>

Copies the head bytes (one copy) and field spans into bytes and fields, which are cleared first, and returns the interpreted facts: with them, OwnedRequestHead::from_parts (or a passport) rebuilds a view without parsing again. Once the vectors have grown to the largest head seen, the copy allocates nothing.

§Errors

None today: a view always has a current head. The Result leaves room for a head that cannot be copied without reading more input.

§Examples
use http_net::{OwnedRequestHead, ServerConn, ServerEvent};

// A passport's buffers, reused for every request.
let (mut bytes, mut fields) = (Vec::with_capacity(4096), Vec::with_capacity(64));
let mut conn = ServerConn::new();
let _ = conn.feed(b"POST /api HTTP/1.1\r\nHost: a\r\nContent-Length: 2\r\n\r\nhi");
let ServerEvent::Request(req) = conn.poll().unwrap() else { panic!() };
let facts = req.copy_into(&mut bytes, &mut fields)?;
assert_eq!(bytes, b"POST /api HTTP/1.1\r\nHost: a\r\nContent-Length: 2\r\n\r\n");
let owned = OwnedRequestHead::from_parts(bytes, fields, facts)?;
assert_eq!(owned.view().content_length(), Some(2));
Source

pub fn to_owned(&self) -> OwnedRequestHead

An owned copy of the head, for keeping it across body events or sending it to another thread.

§Examples
use http_net::{ServerConn, ServerEvent};

let mut conn = ServerConn::new();
let _ = conn.feed(b"GET /keep HTTP/1.1\r\nHost: a\r\n\r\n");
let ServerEvent::Request(req) = conn.poll().unwrap() else { panic!() };
let owned = req.to_owned();
drop(conn);
assert_eq!(owned.view().path(), "/keep");

Trait Implementations§

Source§

impl<'a> Clone for RequestHead<'a>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<'a> Copy for RequestHead<'a>

Source§

impl Debug for RequestHead<'_>

Shows method, target, version, fields, and framing; the values of credential fields are replaced by <redacted N bytes>.

Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<'a> Freeze for RequestHead<'a>

§

impl<'a> RefUnwindSafe for RequestHead<'a>

§

impl<'a> Send for RequestHead<'a>

§

impl<'a> Sync for RequestHead<'a>

§

impl<'a> Unpin for RequestHead<'a>

§

impl<'a> UnsafeUnpin for RequestHead<'a>

§

impl<'a> UnwindSafe for RequestHead<'a>

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 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> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
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.