serenade_http_client/
request.rs1use std::collections::BTreeMap;
4use std::time::Duration;
5
6#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
8pub enum ClientMethod {
9 Get,
11 Post,
13 Put,
15 Patch,
17 Delete,
19 Head,
21}
22
23impl ClientMethod {
24 #[must_use]
26 pub const fn as_str(self) -> &'static str {
27 match self {
28 Self::Get => "GET",
29 Self::Post => "POST",
30 Self::Put => "PUT",
31 Self::Patch => "PATCH",
32 Self::Delete => "DELETE",
33 Self::Head => "HEAD",
34 }
35 }
36}
37
38impl std::fmt::Display for ClientMethod {
39 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40 formatter.write_str(self.as_str())
41 }
42}
43
44#[derive(Clone, Debug, Eq, PartialEq)]
46pub struct ClientRequest {
47 method: ClientMethod,
48 url: String,
49 headers: BTreeMap<String, String>,
50 body: Vec<u8>,
51 timeout: Option<Duration>,
52}
53
54impl ClientRequest {
55 #[must_use]
57 pub fn get(url: impl Into<String>) -> Self {
58 Self::new(ClientMethod::Get, url)
59 }
60
61 #[must_use]
63 pub fn post(url: impl Into<String>) -> Self {
64 Self::new(ClientMethod::Post, url)
65 }
66
67 #[must_use]
69 pub fn put(url: impl Into<String>) -> Self {
70 Self::new(ClientMethod::Put, url)
71 }
72
73 #[must_use]
75 pub fn patch(url: impl Into<String>) -> Self {
76 Self::new(ClientMethod::Patch, url)
77 }
78
79 #[must_use]
81 pub fn delete(url: impl Into<String>) -> Self {
82 Self::new(ClientMethod::Delete, url)
83 }
84
85 #[must_use]
87 pub fn head(url: impl Into<String>) -> Self {
88 Self::new(ClientMethod::Head, url)
89 }
90
91 #[must_use]
93 pub fn new(method: ClientMethod, url: impl Into<String>) -> Self {
94 Self {
95 method,
96 url: url.into(),
97 headers: BTreeMap::new(),
98 body: Vec::new(),
99 timeout: None,
100 }
101 }
102
103 #[must_use]
105 pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
106 self.headers
107 .insert(name.into().to_ascii_lowercase(), value.into());
108 self
109 }
110
111 #[must_use]
113 pub fn body(mut self, body: impl Into<Vec<u8>>) -> Self {
114 self.body = body.into();
115 self
116 }
117
118 #[must_use]
120 pub fn body_text(mut self, text: impl Into<String>) -> Self {
121 self.body = text.into().into_bytes();
122 self.headers
123 .entry("content-type".to_owned())
124 .or_insert_with(|| "text/plain; charset=utf-8".to_owned());
125 self
126 }
127
128 #[must_use]
130 pub const fn timeout(mut self, timeout: Duration) -> Self {
131 self.timeout = Some(timeout);
132 self
133 }
134
135 #[must_use]
137 pub const fn method(&self) -> ClientMethod {
138 self.method
139 }
140
141 #[must_use]
143 pub fn url(&self) -> &str {
144 &self.url
145 }
146
147 #[must_use]
149 pub const fn headers(&self) -> &BTreeMap<String, String> {
150 &self.headers
151 }
152
153 #[must_use]
155 pub fn body_bytes(&self) -> &[u8] {
156 &self.body
157 }
158
159 #[must_use]
161 pub const fn timeout_duration(&self) -> Option<Duration> {
162 self.timeout
163 }
164}