From 85260fb668778a4c6fc1ef523986f7122c1ad74f Mon Sep 17 00:00:00 2001 From: Thomas Date: Sun, 15 Jan 2023 14:45:04 +0100 Subject: [PATCH 1/2] doc: add another custom header example --- src/lib.rs | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index 0d27a810..7cc5ba60 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -71,6 +71,48 @@ //! } //! } //! ``` +//! +//! Another example; the `x-real-ip` is a header set by some reverse proxies, +//! this sets the IP address where the client send the request from. +//! +//! ``` +//! extern crate headers; +//! +//! use headers::{Header, HeaderName, HeaderValue}; +//! use std::net::IpAddr; +//! +//! struct RealIp(IpAddr); +//! +//! static REAL_IP: HeaderName = HeaderName::from_static("x-real-ip"); +//! +//! impl Header for RealIp { +//! fn name() -> &'static HeaderName { +//! &REAL_IP +//! } +//! +//! fn decode<'i, I>(values: &mut I) -> Result +//! where +//! I: Iterator, +//! { +//! let value = values.next().ok_or_else(headers::Error::invalid)?; +//! +//! let real_ip_str = +//! String::from_utf8(value.as_bytes().to_vec()).map_err(|_| headers::Error::invalid())?; +//! let real_ip = real_ip_str.parse().map_err(|_| headers::Error::invalid())?; +//! +//! Ok(RealIp(real_ip)) +//! } +//! +//! fn encode(&self, values: &mut E) +//! where +//! E: Extend, +//! { +//! let value = HeaderValue::from_str(&self.0.to_string()); +//! +//! values.extend(std::iter::once(value.unwrap())); +//! } +//! } +//! ``` extern crate base64; #[macro_use] From 4c4c38f078493ef6a6d2e766df32dfc8e1f34095 Mon Sep 17 00:00:00 2001 From: Thomas Date: Sun, 15 Jan 2023 14:50:58 +0100 Subject: [PATCH 2/2] doc: header value can just be a str in the example --- src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index 7cc5ba60..b076be29 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -97,7 +97,7 @@ //! let value = values.next().ok_or_else(headers::Error::invalid)?; //! //! let real_ip_str = -//! String::from_utf8(value.as_bytes().to_vec()).map_err(|_| headers::Error::invalid())?; +//! std::str::from_utf8(value.as_bytes()).map_err(|_| headers::Error::invalid())?; //! let real_ip = real_ip_str.parse().map_err(|_| headers::Error::invalid())?; //! //! Ok(RealIp(real_ip))