Skip to main content

ling_net/
types.rs

1use std::collections::HashMap;
2
3#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4pub enum HttpMethod {
5    Get,
6    Post,
7    Put,
8    Patch,
9    Delete,
10    Head,
11    Options,
12}
13
14impl HttpMethod {
15    pub fn as_str(self) -> &'static str {
16        match self {
17            Self::Get => "GET",
18            Self::Post => "POST",
19            Self::Put => "PUT",
20            Self::Patch => "PATCH",
21            Self::Delete => "DELETE",
22            Self::Head => "HEAD",
23            Self::Options => "OPTIONS",
24        }
25    }
26}
27
28#[derive(Debug, Clone)]
29pub struct Request {
30    pub method: HttpMethod,
31    pub url: String,
32    pub headers: HashMap<String, String>,
33    pub body: Option<Vec<u8>>,
34}
35
36impl Request {
37    pub fn get(url: impl Into<String>) -> Self {
38        Self {
39            method: HttpMethod::Get,
40            url: url.into(),
41            headers: HashMap::new(),
42            body: None,
43        }
44    }
45
46    pub fn post(url: impl Into<String>, body: impl Into<Vec<u8>>) -> Self {
47        Self {
48            method: HttpMethod::Post,
49            url: url.into(),
50            headers: HashMap::new(),
51            body: Some(body.into()),
52        }
53    }
54
55    pub fn header(mut self, key: impl Into<String>, val: impl Into<String>) -> Self {
56        self.headers.insert(key.into(), val.into());
57        self
58    }
59}
60
61#[derive(Debug, Clone)]
62pub struct Response {
63    pub status: u16,
64    pub headers: HashMap<String, String>,
65    pub body: Vec<u8>,
66}
67
68impl Response {
69    pub fn ok(body: impl Into<Vec<u8>>) -> Self {
70        Self { status: 200, headers: HashMap::new(), body: body.into() }
71    }
72
73    pub fn text(&self) -> &str {
74        std::str::from_utf8(&self.body).unwrap_or("")
75    }
76
77    pub fn is_success(&self) -> bool {
78        self.status >= 200 && self.status < 300
79    }
80}