feather_runtime/http/
request.rs

1use crate::utils::error::Error;
2use bytes::Bytes;
3use http::{Extensions, HeaderMap, Method, Uri, Version};
4use std::{collections::HashMap, fmt};
5
6use super::ConnectionState;
7
8
9#[derive(Debug, Clone)]
10pub struct Request {
11    /// The HTTP method of the request.<br>
12    /// For example, GET, POST, PUT, DELETE, etc.
13    pub method: Method,
14    /// The URI of the request.
15    pub uri: Uri,
16    /// The HTTP version of the request.
17    pub version: Version,
18    /// The headers of the request.
19    pub headers: HeaderMap,
20    /// The body of the request.
21    pub body: Bytes, 
22    /// The extensions of the request.
23    pub extensions: Extensions, 
24    // Connection State(Keep-Alive OR Close) of the Request
25    pub(crate) connection: Option<ConnectionState>,
26}
27
28impl Request {
29    /// Parses the body of the request as Serde JSON Value. Returns an error if the body is not valid JSON.
30    /// This method is useful for parsing JSON payloads in requests.
31    pub fn json(&self) -> Result<serde_json::Value, Error> {
32        serde_json::from_slice(&self.body).map_err(|e| {
33            Error::ParseError(format!("Failed to parse JSON body: {}", e))
34        })
35    }
36    pub fn query(&self) -> Result<HashMap<String,String>, Error>{
37        if let Some(query) = self.uri.query(){
38            serde_urlencoded::from_str(query).map_err(|e|{
39                Error::ParseError(format!("Failed to Parse Query parameters {}",e))
40            })
41        }else{
42            Ok(HashMap::new())
43        }
44    }
45}
46impl fmt::Display for Request {
47    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48        write!(
49            f,
50            "{} for {}: Body Data: {} ",
51            self.method,
52            self.uri,
53            String::from_utf8_lossy(&self.body)
54        ) 
55    }
56}