upnp_rs/common/httpu/
request.rs

1/*!
2What's this all about then?
3*/
4
5use crate::syntax::{
6    HTTP_HEADER_LINE_SEP, HTTP_HEADER_SEP, HTTP_MATCH_ANY_RESOURCE, HTTP_PROTOCOL_NAME,
7    HTTP_PROTOCOL_VERSION,
8};
9use std::collections::HashMap;
10
11// ------------------------------------------------------------------------------------------------
12// Public Types
13// ------------------------------------------------------------------------------------------------
14
15#[derive(Clone, Debug)]
16pub struct Request {
17    pub(crate) message: String,
18    pub(crate) resource: Option<String>,
19    pub(crate) headers: HashMap<String, String>,
20}
21
22// ------------------------------------------------------------------------------------------------
23// Implementations
24// ------------------------------------------------------------------------------------------------
25
26impl Request {
27    fn request_line(&self) -> String {
28        format!(
29            "{} {} {}/{}{}",
30            self.message,
31            match &self.resource {
32                None => HTTP_MATCH_ANY_RESOURCE.to_string(),
33                Some(resource) => resource.clone(),
34            },
35            HTTP_PROTOCOL_NAME,
36            HTTP_PROTOCOL_VERSION,
37            HTTP_HEADER_LINE_SEP,
38        )
39    }
40
41    fn all_headers(&self) -> String {
42        self.headers
43            .iter()
44            .map(|(k, v)| format!("{}{}{}", k, HTTP_HEADER_SEP, v))
45            .collect::<Vec<String>>()
46            .join(HTTP_HEADER_LINE_SEP)
47    }
48
49    fn body(&self) -> String {
50        format!("{}{}", HTTP_HEADER_LINE_SEP, HTTP_HEADER_LINE_SEP)
51    }
52}
53
54impl From<&Request> for String {
55    fn from(rq: &Request) -> Self {
56        format!("{}{}{}", rq.request_line(), rq.all_headers(), rq.body())
57    }
58}