Skip to main content

musdk_common/http_client/
request.rs

1// parts of this file are derived from `reqwest` https://github.com/seanmonstar/reqwest
2//
3// Copyright (c) 2016 Sean McArthur
4//
5// Permission is hereby granted, free of charge, to any person obtaining a copy
6// of this software and associated documentation files (the "Software"), to deal
7// in the Software without restriction, including without limitation the rights
8// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9// copies of the Software, and to permit persons to whom the Software is
10// furnished to do so, subject to the following conditions:
11//
12// The above copyright notice and this permission notice shall be included in
13// all copies or substantial portions of the Software.
14//
15// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21// THE SOFTWARE.
22
23use core::fmt;
24use std::borrow::Cow;
25
26use borsh::{BorshDeserialize, BorshSerialize};
27
28use super::{Body, Header, HttpMethod, Url, Version};
29
30#[derive(BorshSerialize, BorshDeserialize, Clone)]
31pub struct Request<'a> {
32    pub method: HttpMethod,
33    pub url: Url,
34    pub headers: Vec<Header<'a>>,
35    pub body: Body<'a>,
36    pub version: Version,
37}
38
39impl<'a> Request<'a> {
40    /// Constructs a new request.
41    #[inline]
42    pub fn new(method: HttpMethod, url: Url) -> Self {
43        Request {
44            method,
45            url,
46            headers: vec![],
47            body: Cow::Borrowed(&[]),
48            version: Version::default(),
49        }
50    }
51
52    /// Get the content-type header otherwise None if there is no content-type header.
53    pub fn content_type(&self) -> Option<Cow<'a, str>> {
54        self.headers.iter().find_map(|header| {
55            if &header.name.to_lowercase() == "content-type" {
56                Some(header.value.clone())
57            } else {
58                None
59            }
60        })
61    }
62}
63
64impl<'a> fmt::Debug for Request<'a> {
65    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
66        fmt_request_fields(&mut f.debug_struct("Request"), self).finish()
67    }
68}
69
70fn fmt_request_fields<'a, 'b>(
71    f: &'a mut fmt::DebugStruct<'a, 'b>,
72    req: &Request,
73) -> &'a mut fmt::DebugStruct<'a, 'b> {
74    f.field("method", &req.method)
75        .field("url", &req.url)
76        .field("headers", &req.headers)
77}