http/request.rs
1//! HTTP request types.
2//!
3//! This module contains structs related to HTTP requests, notably the
4//! `Request` type itself as well as a builder to create requests. Typically
5//! you'll import the `http::Request` type rather than reaching into this
6//! module itself.
7//!
8//! # Examples
9//!
10//! Creating a `Request` to send
11//!
12//! ```no_run
13//! use http::{Request, Response};
14//!
15//! let mut request = Request::builder()
16//! .uri("https://www.rust-lang.org/")
17//! .header("User-Agent", "my-awesome-agent/1.0");
18//!
19//! if needs_awesome_header() {
20//! request = request.header("Awesome", "yes");
21//! }
22//!
23//! let response = send(request.body(()).unwrap());
24//!
25//! # fn needs_awesome_header() -> bool {
26//! # true
27//! # }
28//! #
29//! fn send(req: Request<()>) -> Response<()> {
30//! // ...
31//! # panic!()
32//! }
33//! ```
34//!
35//! Inspecting a request to see what was sent.
36//!
37//! ```
38//! use http::{Request, Response, StatusCode};
39//!
40//! fn respond_to(req: Request<()>) -> http::Result<Response<()>> {
41//! if req.uri() != "/awesome-url" {
42//! return Response::builder()
43//! .status(StatusCode::NOT_FOUND)
44//! .body(())
45//! }
46//!
47//! let has_awesome_header = req.headers().contains_key("Awesome");
48//! let body = req.body();
49//!
50//! // ...
51//! # panic!()
52//! }
53//! ```
54
55use std::any::Any;
56use std::convert::TryInto;
57use std::fmt;
58
59use crate::header::{HeaderMap, HeaderName, HeaderValue};
60use crate::method::Method;
61use crate::version::Version;
62use crate::{Extensions, Result, Uri};
63
64/// Represents an HTTP request.
65///
66/// An HTTP request consists of a head and a potentially optional body. The body
67/// component is generic, enabling arbitrary types to represent the HTTP body.
68/// For example, the body could be `Vec<u8>`, a `Stream` of byte chunks, or a
69/// value that has been deserialized.
70///
71/// # Examples
72///
73/// Creating a `Request` to send
74///
75/// ```no_run
76/// use http::{Request, Response};
77///
78/// let mut request = Request::builder()
79/// .uri("https://www.rust-lang.org/")
80/// .header("User-Agent", "my-awesome-agent/1.0");
81///
82/// if needs_awesome_header() {
83/// request = request.header("Awesome", "yes");
84/// }
85///
86/// let response = send(request.body(()).unwrap());
87///
88/// # fn needs_awesome_header() -> bool {
89/// # true
90/// # }
91/// #
92/// fn send(req: Request<()>) -> Response<()> {
93/// // ...
94/// # panic!()
95/// }
96/// ```
97///
98/// Inspecting a request to see what was sent.
99///
100/// ```
101/// use http::{Request, Response, StatusCode};
102///
103/// fn respond_to(req: Request<()>) -> http::Result<Response<()>> {
104/// if req.uri() != "/awesome-url" {
105/// return Response::builder()
106/// .status(StatusCode::NOT_FOUND)
107/// .body(())
108/// }
109///
110/// let has_awesome_header = req.headers().contains_key("Awesome");
111/// let body = req.body();
112///
113/// // ...
114/// # panic!()
115/// }
116/// ```
117///
118/// Deserialize a request of bytes via json:
119///
120/// ```
121/// use http::Request;
122/// use serde::de;
123///
124/// fn deserialize<T>(req: Request<Vec<u8>>) -> serde_json::Result<Request<T>>
125/// where for<'de> T: de::Deserialize<'de>,
126/// {
127/// let (parts, body) = req.into_parts();
128/// let body = serde_json::from_slice(&body)?;
129/// Ok(Request::from_parts(parts, body))
130/// }
131/// #
132/// # fn main() {}
133/// ```
134///
135/// Or alternatively, serialize the body of a request to json
136///
137/// ```
138/// use http::Request;
139/// use serde::ser;
140///
141/// fn serialize<T>(req: Request<T>) -> serde_json::Result<Request<Vec<u8>>>
142/// where T: ser::Serialize,
143/// {
144/// let (parts, body) = req.into_parts();
145/// let body = serde_json::to_vec(&body)?;
146/// Ok(Request::from_parts(parts, body))
147/// }
148/// #
149/// # fn main() {}
150/// ```
151#[derive(Clone)]
152pub struct Request<T> {
153 head: Parts,
154 body: T,
155}
156
157/// Component parts of an HTTP `Request`
158///
159/// The HTTP request head consists of a method, uri, version, and a set of
160/// header fields.
161#[derive(Clone)]
162pub struct Parts {
163 /// The request's method
164 pub method: Method,
165
166 /// The request's URI
167 pub uri: Uri,
168
169 /// The request's version
170 pub version: Version,
171
172 /// The request's headers
173 pub headers: HeaderMap<HeaderValue>,
174
175 /// The request's extensions
176 pub extensions: Extensions,
177
178 _priv: (),
179}
180
181/// An HTTP request builder
182///
183/// This type can be used to construct an instance of `Request`
184/// through a builder-like pattern.
185#[derive(Debug)]
186pub struct Builder {
187 inner: Result<Parts>,
188}
189
190impl Request<()> {
191 /// Creates a new builder-style object to manufacture a `Request`
192 ///
193 /// This method returns an instance of `Builder` which can be used to
194 /// create a `Request`.
195 ///
196 /// # Examples
197 ///
198 /// ```
199 /// # use http::*;
200 /// let request = Request::builder()
201 /// .method("GET")
202 /// .uri("https://www.rust-lang.org/")
203 /// .header("X-Custom-Foo", "Bar")
204 /// .body(())
205 /// .unwrap();
206 /// ```
207 #[inline]
208 pub fn builder() -> Builder {
209 Builder::new()
210 }
211
212 /// Creates a new `Builder` initialized with a GET method and the given URI.
213 ///
214 /// This method returns an instance of `Builder` which can be used to
215 /// create a `Request`.
216 ///
217 /// # Example
218 ///
219 /// ```
220 /// # use http::*;
221 ///
222 /// let request = Request::get("https://www.rust-lang.org/")
223 /// .body(())
224 /// .unwrap();
225 /// ```
226 pub fn get<T>(uri: T) -> Builder
227 where
228 T: TryInto<Uri>,
229 <T as TryInto<Uri>>::Error: Into<crate::Error>,
230 {
231 Builder::new().method(Method::GET).uri(uri)
232 }
233
234 /// Creates a new `Builder` initialized with a PUT method and the given URI.
235 ///
236 /// This method returns an instance of `Builder` which can be used to
237 /// create a `Request`.
238 ///
239 /// # Example
240 ///
241 /// ```
242 /// # use http::*;
243 ///
244 /// let request = Request::put("https://www.rust-lang.org/")
245 /// .body(())
246 /// .unwrap();
247 /// ```
248 pub fn put<T>(uri: T) -> Builder
249 where
250 T: TryInto<Uri>,
251 <T as TryInto<Uri>>::Error: Into<crate::Error>,
252 {
253 Builder::new().method(Method::PUT).uri(uri)
254 }
255
256 /// Creates a new `Builder` initialized with a POST method and the given URI.
257 ///
258 /// This method returns an instance of `Builder` which can be used to
259 /// create a `Request`.
260 ///
261 /// # Example
262 ///
263 /// ```
264 /// # use http::*;
265 ///
266 /// let request = Request::post("https://www.rust-lang.org/")
267 /// .body(())
268 /// .unwrap();
269 /// ```
270 pub fn post<T>(uri: T) -> Builder
271 where
272 T: TryInto<Uri>,
273 <T as TryInto<Uri>>::Error: Into<crate::Error>,
274 {
275 Builder::new().method(Method::POST).uri(uri)
276 }
277
278 /// Creates a new `Builder` initialized with a DELETE method and the given URI.
279 ///
280 /// This method returns an instance of `Builder` which can be used to
281 /// create a `Request`.
282 ///
283 /// # Example
284 ///
285 /// ```
286 /// # use http::*;
287 ///
288 /// let request = Request::delete("https://www.rust-lang.org/")
289 /// .body(())
290 /// .unwrap();
291 /// ```
292 pub fn delete<T>(uri: T) -> Builder
293 where
294 T: TryInto<Uri>,
295 <T as TryInto<Uri>>::Error: Into<crate::Error>,
296 {
297 Builder::new().method(Method::DELETE).uri(uri)
298 }
299
300 /// Creates a new `Builder` initialized with an OPTIONS method and the given URI.
301 ///
302 /// This method returns an instance of `Builder` which can be used to
303 /// create a `Request`.
304 ///
305 /// # Example
306 ///
307 /// ```
308 /// # use http::*;
309 ///
310 /// let request = Request::options("https://www.rust-lang.org/")
311 /// .body(())
312 /// .unwrap();
313 /// # assert_eq!(*request.method(), Method::OPTIONS);
314 /// ```
315 pub fn options<T>(uri: T) -> Builder
316 where
317 T: TryInto<Uri>,
318 <T as TryInto<Uri>>::Error: Into<crate::Error>,
319 {
320 Builder::new().method(Method::OPTIONS).uri(uri)
321 }
322
323 /// Creates a new `Builder` initialized with a HEAD method and the given URI.
324 ///
325 /// This method returns an instance of `Builder` which can be used to
326 /// create a `Request`.
327 ///
328 /// # Example
329 ///
330 /// ```
331 /// # use http::*;
332 ///
333 /// let request = Request::head("https://www.rust-lang.org/")
334 /// .body(())
335 /// .unwrap();
336 /// ```
337 pub fn head<T>(uri: T) -> Builder
338 where
339 T: TryInto<Uri>,
340 <T as TryInto<Uri>>::Error: Into<crate::Error>,
341 {
342 Builder::new().method(Method::HEAD).uri(uri)
343 }
344
345 /// Creates a new `Builder` initialized with a CONNECT method and the given URI.
346 ///
347 /// This method returns an instance of `Builder` which can be used to
348 /// create a `Request`.
349 ///
350 /// # Example
351 ///
352 /// ```
353 /// # use http::*;
354 ///
355 /// let request = Request::connect("https://www.rust-lang.org/")
356 /// .body(())
357 /// .unwrap();
358 /// ```
359 pub fn connect<T>(uri: T) -> Builder
360 where
361 T: TryInto<Uri>,
362 <T as TryInto<Uri>>::Error: Into<crate::Error>,
363 {
364 Builder::new().method(Method::CONNECT).uri(uri)
365 }
366
367 /// Creates a new `Builder` initialized with a PATCH method and the given URI.
368 ///
369 /// This method returns an instance of `Builder` which can be used to
370 /// create a `Request`.
371 ///
372 /// # Example
373 ///
374 /// ```
375 /// # use http::*;
376 ///
377 /// let request = Request::patch("https://www.rust-lang.org/")
378 /// .body(())
379 /// .unwrap();
380 /// ```
381 pub fn patch<T>(uri: T) -> Builder
382 where
383 T: TryInto<Uri>,
384 <T as TryInto<Uri>>::Error: Into<crate::Error>,
385 {
386 Builder::new().method(Method::PATCH).uri(uri)
387 }
388
389 /// Creates a new `Builder` initialized with a TRACE method and the given URI.
390 ///
391 /// This method returns an instance of `Builder` which can be used to
392 /// create a `Request`.
393 ///
394 /// # Example
395 ///
396 /// ```
397 /// # use http::*;
398 ///
399 /// let request = Request::trace("https://www.rust-lang.org/")
400 /// .body(())
401 /// .unwrap();
402 /// ```
403 pub fn trace<T>(uri: T) -> Builder
404 where
405 T: TryInto<Uri>,
406 <T as TryInto<Uri>>::Error: Into<crate::Error>,
407 {
408 Builder::new().method(Method::TRACE).uri(uri)
409 }
410
411 // This is purposefully excluded because of potential conflict with the
412 // URI query.
413 // pub fn query() -> Builder
414}
415
416impl<T> Request<T> {
417 /// Creates a new blank `Request` with the body
418 ///
419 /// The component parts of this request will be set to their default, e.g.
420 /// the GET method, no headers, etc.
421 ///
422 /// # Examples
423 ///
424 /// ```
425 /// # use http::*;
426 /// let request = Request::new("hello world");
427 ///
428 /// assert_eq!(*request.method(), Method::GET);
429 /// assert_eq!(*request.body(), "hello world");
430 /// ```
431 #[inline]
432 pub fn new(body: T) -> Request<T> {
433 Request {
434 head: Parts::new(),
435 body,
436 }
437 }
438
439 /// Creates a new `Request` with the given components parts and body.
440 ///
441 /// # Examples
442 ///
443 /// ```
444 /// # use http::*;
445 /// let request = Request::new("hello world");
446 /// let (mut parts, body) = request.into_parts();
447 /// parts.method = Method::POST;
448 ///
449 /// let request = Request::from_parts(parts, body);
450 /// ```
451 #[inline]
452 pub fn from_parts(parts: Parts, body: T) -> Request<T> {
453 Request { head: parts, body }
454 }
455
456 /// Returns a reference to the associated HTTP method.
457 ///
458 /// # Examples
459 ///
460 /// ```
461 /// # use http::*;
462 /// let request: Request<()> = Request::default();
463 /// assert_eq!(*request.method(), Method::GET);
464 /// ```
465 #[inline]
466 pub fn method(&self) -> &Method {
467 &self.head.method
468 }
469
470 /// Returns a mutable reference to the associated HTTP method.
471 ///
472 /// # Examples
473 ///
474 /// ```
475 /// # use http::*;
476 /// let mut request: Request<()> = Request::default();
477 /// *request.method_mut() = Method::PUT;
478 /// assert_eq!(*request.method(), Method::PUT);
479 /// ```
480 #[inline]
481 pub fn method_mut(&mut self) -> &mut Method {
482 &mut self.head.method
483 }
484
485 /// Returns a reference to the associated URI.
486 ///
487 /// # Examples
488 ///
489 /// ```
490 /// # use http::*;
491 /// let request: Request<()> = Request::default();
492 /// assert_eq!(*request.uri(), *"/");
493 /// ```
494 #[inline]
495 pub fn uri(&self) -> &Uri {
496 &self.head.uri
497 }
498
499 /// Returns a mutable reference to the associated URI.
500 ///
501 /// # Examples
502 ///
503 /// ```
504 /// # use http::*;
505 /// let mut request: Request<()> = Request::default();
506 /// *request.uri_mut() = "/hello".parse().unwrap();
507 /// assert_eq!(*request.uri(), *"/hello");
508 /// ```
509 #[inline]
510 pub fn uri_mut(&mut self) -> &mut Uri {
511 &mut self.head.uri
512 }
513
514 /// Returns the associated version.
515 ///
516 /// # Examples
517 ///
518 /// ```
519 /// # use http::*;
520 /// let request: Request<()> = Request::default();
521 /// assert_eq!(request.version(), Version::HTTP_11);
522 /// ```
523 #[inline]
524 pub fn version(&self) -> Version {
525 self.head.version
526 }
527
528 /// Returns a mutable reference to the associated version.
529 ///
530 /// # Examples
531 ///
532 /// ```
533 /// # use http::*;
534 /// let mut request: Request<()> = Request::default();
535 /// *request.version_mut() = Version::HTTP_2;
536 /// assert_eq!(request.version(), Version::HTTP_2);
537 /// ```
538 #[inline]
539 pub fn version_mut(&mut self) -> &mut Version {
540 &mut self.head.version
541 }
542
543 /// Returns a reference to the associated header field map.
544 ///
545 /// # Examples
546 ///
547 /// ```
548 /// # use http::*;
549 /// let request: Request<()> = Request::default();
550 /// assert!(request.headers().is_empty());
551 /// ```
552 #[inline]
553 pub fn headers(&self) -> &HeaderMap<HeaderValue> {
554 &self.head.headers
555 }
556
557 /// Returns a mutable reference to the associated header field map.
558 ///
559 /// # Examples
560 ///
561 /// ```
562 /// # use http::*;
563 /// # use http::header::*;
564 /// let mut request: Request<()> = Request::default();
565 /// request.headers_mut().insert(HOST, HeaderValue::from_static("world"));
566 /// assert!(!request.headers().is_empty());
567 /// ```
568 #[inline]
569 pub fn headers_mut(&mut self) -> &mut HeaderMap<HeaderValue> {
570 &mut self.head.headers
571 }
572
573 /// Returns a reference to the associated extensions.
574 ///
575 /// # Examples
576 ///
577 /// ```
578 /// # use http::*;
579 /// let request: Request<()> = Request::default();
580 /// assert!(request.extensions().get::<i32>().is_none());
581 /// ```
582 #[inline]
583 pub fn extensions(&self) -> &Extensions {
584 &self.head.extensions
585 }
586
587 /// Returns a mutable reference to the associated extensions.
588 ///
589 /// # Examples
590 ///
591 /// ```
592 /// # use http::*;
593 /// # use http::header::*;
594 /// let mut request: Request<()> = Request::default();
595 /// request.extensions_mut().insert("hello");
596 /// assert_eq!(request.extensions().get(), Some(&"hello"));
597 /// ```
598 #[inline]
599 pub fn extensions_mut(&mut self) -> &mut Extensions {
600 &mut self.head.extensions
601 }
602
603 /// Returns a reference to the associated HTTP body.
604 ///
605 /// # Examples
606 ///
607 /// ```
608 /// # use http::*;
609 /// let request: Request<String> = Request::default();
610 /// assert!(request.body().is_empty());
611 /// ```
612 #[inline]
613 pub fn body(&self) -> &T {
614 &self.body
615 }
616
617 /// Returns a mutable reference to the associated HTTP body.
618 ///
619 /// # Examples
620 ///
621 /// ```
622 /// # use http::*;
623 /// let mut request: Request<String> = Request::default();
624 /// request.body_mut().push_str("hello world");
625 /// assert!(!request.body().is_empty());
626 /// ```
627 #[inline]
628 pub fn body_mut(&mut self) -> &mut T {
629 &mut self.body
630 }
631
632 /// Consumes the request, returning just the body.
633 ///
634 /// # Examples
635 ///
636 /// ```
637 /// # use http::Request;
638 /// let request = Request::new(10);
639 /// let body = request.into_body();
640 /// assert_eq!(body, 10);
641 /// ```
642 #[inline]
643 pub fn into_body(self) -> T {
644 self.body
645 }
646
647 /// Consumes the request returning the head and body parts.
648 ///
649 /// # Examples
650 ///
651 /// ```
652 /// # use http::*;
653 /// let request = Request::new(());
654 /// let (parts, body) = request.into_parts();
655 /// assert_eq!(parts.method, Method::GET);
656 /// ```
657 #[inline]
658 pub fn into_parts(self) -> (Parts, T) {
659 (self.head, self.body)
660 }
661
662 /// Consumes the request returning a new request with body mapped to the
663 /// return type of the passed in function.
664 ///
665 /// # Examples
666 ///
667 /// ```
668 /// # use http::*;
669 /// let request = Request::builder().body("some string").unwrap();
670 /// let mapped_request: Request<&[u8]> = request.map(|b| {
671 /// assert_eq!(b, "some string");
672 /// b.as_bytes()
673 /// });
674 /// assert_eq!(mapped_request.body(), &"some string".as_bytes());
675 /// ```
676 #[inline]
677 pub fn map<F, U>(self, f: F) -> Request<U>
678 where
679 F: FnOnce(T) -> U,
680 {
681 Request {
682 body: f(self.body),
683 head: self.head,
684 }
685 }
686}
687
688impl<T: Default> Default for Request<T> {
689 fn default() -> Request<T> {
690 Request::new(T::default())
691 }
692}
693
694impl<T: fmt::Debug> fmt::Debug for Request<T> {
695 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
696 f.debug_struct("Request")
697 .field("method", self.method())
698 .field("uri", self.uri())
699 .field("version", &self.version())
700 .field("headers", self.headers())
701 // omits Extensions because not useful
702 .field("body", self.body())
703 .finish()
704 }
705}
706
707impl Parts {
708 /// Creates a new default instance of `Parts`
709 fn new() -> Parts {
710 Parts {
711 method: Method::default(),
712 uri: Uri::default(),
713 version: Version::default(),
714 headers: HeaderMap::default(),
715 extensions: Extensions::default(),
716 _priv: (),
717 }
718 }
719}
720
721impl fmt::Debug for Parts {
722 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
723 f.debug_struct("Parts")
724 .field("method", &self.method)
725 .field("uri", &self.uri)
726 .field("version", &self.version)
727 .field("headers", &self.headers)
728 // omits Extensions because not useful
729 // omits _priv because not useful
730 .finish()
731 }
732}
733
734impl Builder {
735 /// Creates a new default instance of `Builder` to construct a `Request`.
736 ///
737 /// # Examples
738 ///
739 /// ```
740 /// # use http::*;
741 ///
742 /// let req = request::Builder::new()
743 /// .method("POST")
744 /// .body(())
745 /// .unwrap();
746 /// ```
747 #[inline]
748 pub fn new() -> Builder {
749 Builder::default()
750 }
751
752 /// Set the HTTP method for this request.
753 ///
754 /// By default this is `GET`.
755 ///
756 /// # Examples
757 ///
758 /// ```
759 /// # use http::*;
760 ///
761 /// let req = Request::builder()
762 /// .method("POST")
763 /// .body(())
764 /// .unwrap();
765 /// ```
766 pub fn method<T>(self, method: T) -> Builder
767 where
768 T: TryInto<Method>,
769 <T as TryInto<Method>>::Error: Into<crate::Error>,
770 {
771 self.and_then(move |mut head| {
772 let method = method.try_into().map_err(Into::into)?;
773 head.method = method;
774 Ok(head)
775 })
776 }
777
778 /// Get the HTTP Method for this request.
779 ///
780 /// By default this is `GET`. If builder has error, returns None.
781 ///
782 /// # Examples
783 ///
784 /// ```
785 /// # use http::*;
786 ///
787 /// let mut req = Request::builder();
788 /// assert_eq!(req.method_ref(),Some(&Method::GET));
789 ///
790 /// req = req.method("POST");
791 /// assert_eq!(req.method_ref(),Some(&Method::POST));
792 /// ```
793 pub fn method_ref(&self) -> Option<&Method> {
794 self.inner.as_ref().ok().map(|h| &h.method)
795 }
796
797 /// Set the URI for this request.
798 ///
799 /// By default this is `/`.
800 ///
801 /// # Examples
802 ///
803 /// ```
804 /// # use http::*;
805 ///
806 /// let req = Request::builder()
807 /// .uri("https://www.rust-lang.org/")
808 /// .body(())
809 /// .unwrap();
810 /// ```
811 pub fn uri<T>(self, uri: T) -> Builder
812 where
813 T: TryInto<Uri>,
814 <T as TryInto<Uri>>::Error: Into<crate::Error>,
815 {
816 self.and_then(move |mut head| {
817 head.uri = uri.try_into().map_err(Into::into)?;
818 Ok(head)
819 })
820 }
821
822 /// Get the URI for this request
823 ///
824 /// By default this is `/`.
825 ///
826 /// # Examples
827 ///
828 /// ```
829 /// # use http::*;
830 ///
831 /// let mut req = Request::builder();
832 /// assert_eq!(req.uri_ref().unwrap(), "/" );
833 ///
834 /// req = req.uri("https://www.rust-lang.org/");
835 /// assert_eq!(req.uri_ref().unwrap(), "https://www.rust-lang.org/" );
836 /// ```
837 pub fn uri_ref(&self) -> Option<&Uri> {
838 self.inner.as_ref().ok().map(|h| &h.uri)
839 }
840
841 /// Set the HTTP version for this request.
842 ///
843 /// By default this is HTTP/1.1
844 ///
845 /// # Examples
846 ///
847 /// ```
848 /// # use http::*;
849 ///
850 /// let req = Request::builder()
851 /// .version(Version::HTTP_2)
852 /// .body(())
853 /// .unwrap();
854 /// ```
855 pub fn version(self, version: Version) -> Builder {
856 self.and_then(move |mut head| {
857 head.version = version;
858 Ok(head)
859 })
860 }
861
862 /// Get the HTTP version for this request
863 ///
864 /// By default this is HTTP/1.1.
865 ///
866 /// # Examples
867 ///
868 /// ```
869 /// # use http::*;
870 ///
871 /// let mut req = Request::builder();
872 /// assert_eq!(req.version_ref().unwrap(), &Version::HTTP_11 );
873 ///
874 /// req = req.version(Version::HTTP_2);
875 /// assert_eq!(req.version_ref().unwrap(), &Version::HTTP_2 );
876 /// ```
877 pub fn version_ref(&self) -> Option<&Version> {
878 self.inner.as_ref().ok().map(|h| &h.version)
879 }
880
881 /// Appends a header to this request builder.
882 ///
883 /// This function will append the provided key/value as a header to the
884 /// internal `HeaderMap` being constructed. Essentially this is equivalent
885 /// to calling `HeaderMap::append`.
886 ///
887 /// # Examples
888 ///
889 /// ```
890 /// # use http::*;
891 /// # use http::header::HeaderValue;
892 ///
893 /// let req = Request::builder()
894 /// .header("Accept", "text/html")
895 /// .header("X-Custom-Foo", "bar")
896 /// .body(())
897 /// .unwrap();
898 /// ```
899 pub fn header<K, V>(self, key: K, value: V) -> Builder
900 where
901 K: TryInto<HeaderName>,
902 <K as TryInto<HeaderName>>::Error: Into<crate::Error>,
903 V: TryInto<HeaderValue>,
904 <V as TryInto<HeaderValue>>::Error: Into<crate::Error>,
905 {
906 self.and_then(move |mut head| {
907 let name = key.try_into().map_err(Into::into)?;
908 let value = value.try_into().map_err(Into::into)?;
909 head.headers.try_append(name, value)?;
910 Ok(head)
911 })
912 }
913
914 /// Get header on this request builder.
915 /// when builder has error returns None
916 ///
917 /// # Example
918 ///
919 /// ```
920 /// # use http::Request;
921 /// let req = Request::builder()
922 /// .header("Accept", "text/html")
923 /// .header("X-Custom-Foo", "bar");
924 /// let headers = req.headers_ref().unwrap();
925 /// assert_eq!( headers["Accept"], "text/html" );
926 /// assert_eq!( headers["X-Custom-Foo"], "bar" );
927 /// ```
928 pub fn headers_ref(&self) -> Option<&HeaderMap<HeaderValue>> {
929 self.inner.as_ref().ok().map(|h| &h.headers)
930 }
931
932 /// Get headers on this request builder.
933 ///
934 /// When builder has error returns None.
935 ///
936 /// # Example
937 ///
938 /// ```
939 /// # use http::{header::HeaderValue, Request};
940 /// let mut req = Request::builder();
941 /// {
942 /// let headers = req.headers_mut().unwrap();
943 /// headers.insert("Accept", HeaderValue::from_static("text/html"));
944 /// headers.insert("X-Custom-Foo", HeaderValue::from_static("bar"));
945 /// }
946 /// let headers = req.headers_ref().unwrap();
947 /// assert_eq!( headers["Accept"], "text/html" );
948 /// assert_eq!( headers["X-Custom-Foo"], "bar" );
949 /// ```
950 pub fn headers_mut(&mut self) -> Option<&mut HeaderMap<HeaderValue>> {
951 self.inner.as_mut().ok().map(|h| &mut h.headers)
952 }
953
954 /// Adds an extension to this builder
955 ///
956 /// # Examples
957 ///
958 /// ```
959 /// # use http::*;
960 ///
961 /// let req = Request::builder()
962 /// .extension("My Extension")
963 /// .body(())
964 /// .unwrap();
965 ///
966 /// assert_eq!(req.extensions().get::<&'static str>(),
967 /// Some(&"My Extension"));
968 /// ```
969 pub fn extension<T>(self, extension: T) -> Builder
970 where
971 T: Clone + Any + Send + Sync + 'static,
972 {
973 self.and_then(move |mut head| {
974 head.extensions.insert(extension);
975 Ok(head)
976 })
977 }
978
979 /// Get a reference to the extensions for this request builder.
980 ///
981 /// If the builder has an error, this returns `None`.
982 ///
983 /// # Example
984 ///
985 /// ```
986 /// # use http::Request;
987 /// let req = Request::builder().extension("My Extension").extension(5u32);
988 /// let extensions = req.extensions_ref().unwrap();
989 /// assert_eq!(extensions.get::<&'static str>(), Some(&"My Extension"));
990 /// assert_eq!(extensions.get::<u32>(), Some(&5u32));
991 /// ```
992 pub fn extensions_ref(&self) -> Option<&Extensions> {
993 self.inner.as_ref().ok().map(|h| &h.extensions)
994 }
995
996 /// Get a mutable reference to the extensions for this request builder.
997 ///
998 /// If the builder has an error, this returns `None`.
999 ///
1000 /// # Example
1001 ///
1002 /// ```
1003 /// # use http::Request;
1004 /// let mut req = Request::builder().extension("My Extension");
1005 /// let mut extensions = req.extensions_mut().unwrap();
1006 /// assert_eq!(extensions.get::<&'static str>(), Some(&"My Extension"));
1007 /// extensions.insert(5u32);
1008 /// assert_eq!(extensions.get::<u32>(), Some(&5u32));
1009 /// ```
1010 pub fn extensions_mut(&mut self) -> Option<&mut Extensions> {
1011 self.inner.as_mut().ok().map(|h| &mut h.extensions)
1012 }
1013
1014 /// "Consumes" this builder, using the provided `body` to return a
1015 /// constructed `Request`.
1016 ///
1017 /// # Errors
1018 ///
1019 /// This function may return an error if any previously configured argument
1020 /// failed to parse or get converted to the internal representation. For
1021 /// example if an invalid `head` was specified via `header("Foo",
1022 /// "Bar\r\n")` the error will be returned when this function is called
1023 /// rather than when `header` was called.
1024 ///
1025 /// # Examples
1026 ///
1027 /// ```
1028 /// # use http::*;
1029 ///
1030 /// let request = Request::builder()
1031 /// .body(())
1032 /// .unwrap();
1033 /// ```
1034 pub fn body<T>(self, body: T) -> Result<Request<T>> {
1035 self.inner.map(move |head| Request { head, body })
1036 }
1037
1038 // private
1039
1040 fn and_then<F>(self, func: F) -> Self
1041 where
1042 F: FnOnce(Parts) -> Result<Parts>,
1043 {
1044 Builder {
1045 inner: self.inner.and_then(func),
1046 }
1047 }
1048}
1049
1050impl Default for Builder {
1051 #[inline]
1052 fn default() -> Builder {
1053 Builder {
1054 inner: Ok(Parts::new()),
1055 }
1056 }
1057}
1058
1059#[cfg(test)]
1060mod tests {
1061 use super::*;
1062
1063 #[test]
1064 fn it_can_map_a_body_from_one_type_to_another() {
1065 let request = Request::builder().body("some string").unwrap();
1066 let mapped_request = request.map(|s| {
1067 assert_eq!(s, "some string");
1068 123u32
1069 });
1070 assert_eq!(mapped_request.body(), &123u32);
1071 }
1072}