rama_http_headers/common/upgrade.rs
1use rama_http_types::HeaderValue;
2
3/// `Upgrade` header, defined in [RFC7230](https://datatracker.ietf.org/doc/html/rfc7230#section-6.7)
4///
5/// The `Upgrade` header field is intended to provide a simple mechanism
6/// for transitioning from HTTP/1.1 to some other protocol on the same
7/// connection. A client MAY send a list of protocols in the Upgrade
8/// header field of a request to invite the server to switch to one or
9/// more of those protocols, in order of descending preference, before
10/// sending the final response. A server MAY ignore a received Upgrade
11/// header field if it wishes to continue using the current protocol on
12/// that connection. Upgrade cannot be used to insist on a protocol
13/// change.
14///
15/// ## ABNF
16///
17/// ```text
18/// Upgrade = 1#protocol
19///
20/// protocol = protocol-name ["/" protocol-version]
21/// protocol-name = token
22/// protocol-version = token
23/// ```
24///
25/// ## Example values
26///
27/// * `HTTP/2.0, SHTTP/1.3, IRC/6.9, RTA/x11`
28///
29/// # Note
30///
31/// In practice, the `Upgrade` header is never that complicated. In most cases,
32/// it is only ever a single value, such as `"websocket"`.
33///
34/// # Examples
35///
36/// ```
37/// use rama_http_headers::Upgrade;
38///
39/// let ws = Upgrade::websocket();
40/// ```
41#[derive(Clone, Debug, PartialEq)]
42pub struct Upgrade(HeaderValue);
43
44derive_header! {
45 Upgrade(_),
46 name: UPGRADE
47}
48
49impl Upgrade {
50 #[inline]
51 pub fn as_bytes(&self) -> &[u8] {
52 self.0.as_ref()
53 }
54}
55
56impl AsRef<[u8]> for Upgrade {
57 #[inline]
58 fn as_ref(&self) -> &[u8] {
59 self.0.as_ref()
60 }
61}
62
63impl Upgrade {
64 /// Constructs an `Upgrade: websocket` header.
65 #[must_use]
66 pub fn websocket() -> Self {
67 Self(HeaderValue::from_static("websocket"))
68 }
69
70 /// Returns true if this is an `Upgrade: websocket` header.
71 pub fn is_websocket(&self) -> bool {
72 self.0
73 .as_bytes()
74 .trim_ascii()
75 .eq_ignore_ascii_case(b"websocket")
76 }
77}