1use std::any::{Any, TypeId};
5use std::collections::HashMap;
6
7use bytes::Bytes;
8use hyper::{Method, StatusCode};
9
10use crate::error::{Error, Result};
11
12#[derive(Default)]
15pub struct Context {
16 inner: HashMap<TypeId, Box<dyn Any + Send + Sync>>,
17}
18
19impl Context {
20 pub fn insert<T: Any + Send + Sync>(&mut self, value: T) {
21 self.inner.insert(TypeId::of::<T>(), Box::new(value));
22 }
23
24 pub fn get<T: Any + Send + Sync>(&self) -> Option<&T> {
25 self.inner
26 .get(&TypeId::of::<T>())
27 .and_then(|b| b.downcast_ref::<T>())
28 }
29
30 pub fn get_mut<T: Any + Send + Sync>(&mut self) -> Option<&mut T> {
31 self.inner
32 .get_mut(&TypeId::of::<T>())
33 .and_then(|b| b.downcast_mut::<T>())
34 }
35}
36
37pub struct Request {
38 method: Method,
39 path: String,
40 query: String,
41 headers: HashMap<String, String>,
42 params: HashMap<String, String>,
43 body: Bytes,
44 ctx: Context,
45}
46
47impl Request {
48 pub(crate) fn new(
49 method: Method,
50 path: String,
51 query: String,
52 headers: HashMap<String, String>,
53 body: Bytes,
54 ) -> Self {
55 Self {
56 method,
57 path,
58 query,
59 headers,
60 params: HashMap::new(),
61 body,
62 ctx: Context::default(),
63 }
64 }
65
66 pub fn method(&self) -> &Method {
67 &self.method
68 }
69
70 pub fn path(&self) -> &str {
71 &self.path
72 }
73
74 pub fn query_string(&self) -> &str {
75 &self.query
76 }
77
78 pub fn query(&self) -> FormData {
79 FormData::from_urlencoded(&self.query)
80 }
81
82 pub fn header(&self, name: &str) -> Option<&str> {
83 self.headers
84 .get(&name.to_ascii_lowercase())
85 .map(|s| s.as_str())
86 }
87
88 pub fn param(&self, name: &str) -> Option<&str> {
89 self.params.get(name).map(|s| s.as_str())
90 }
91
92 pub fn body(&self) -> &[u8] {
93 &self.body
94 }
95
96 pub fn body_text(&self) -> Result<&str> {
97 std::str::from_utf8(&self.body)
98 .map_err(|_| Error::BadRequest("body is not valid utf-8".into()))
99 }
100
101 pub fn form(&self) -> Result<FormData> {
102 let text = self.body_text()?;
103 Ok(FormData::from_urlencoded(text))
104 }
105
106 pub fn ctx(&self) -> &Context {
107 &self.ctx
108 }
109
110 pub fn ctx_mut(&mut self) -> &mut Context {
111 &mut self.ctx
112 }
113
114 pub(crate) fn set_params(&mut self, params: HashMap<String, String>) {
115 self.params = params;
116 }
117}
118
119#[derive(Debug, Default, Clone)]
122pub struct FormData {
123 fields: HashMap<String, String>,
124}
125
126impl FormData {
127 pub fn from_urlencoded(input: &str) -> Self {
128 let mut fields = HashMap::new();
129 for pair in input.split('&') {
130 if pair.is_empty() {
131 continue;
132 }
133 let (raw_key, raw_val) = match pair.split_once('=') {
134 Some((k, v)) => (k, v),
135 None => (pair, ""),
136 };
137 let key = decode(raw_key);
138 let val = decode(raw_val);
139 fields.insert(key, val);
140 }
141 Self { fields }
142 }
143
144 pub fn get(&self, key: &str) -> Option<&str> {
145 self.fields.get(key).map(|s| s.as_str())
146 }
147
148 pub fn required(&self, key: &str) -> Result<&str> {
149 self.get(key)
150 .ok_or_else(|| Error::BadRequest(format!("field {key} is required")))
151 }
152
153 pub fn bool_flag(&self, key: &str) -> bool {
154 matches!(self.get(key), Some("on" | "true" | "1" | "yes"))
156 }
157
158 pub fn contains(&self, key: &str) -> bool {
159 self.fields.contains_key(key)
160 }
161
162 pub fn as_map(&self) -> &HashMap<String, String> {
163 &self.fields
164 }
165}
166
167fn decode(s: &str) -> String {
168 let spaced = s.replace('+', " ");
169 urlencoding::decode(&spaced)
170 .map(|c| c.into_owned())
171 .unwrap_or(spaced)
172}
173
174pub struct Response {
176 pub status: StatusCode,
177 pub headers: Vec<(String, String)>,
178 pub body: Bytes,
179}
180
181impl Response {
182 pub fn new(status: StatusCode, body: impl Into<Bytes>) -> Self {
183 Self {
184 status,
185 headers: Vec::new(),
186 body: body.into(),
187 }
188 }
189
190 pub fn ok(body: impl Into<Bytes>) -> Self {
191 Self::new(StatusCode::OK, body)
192 }
193
194 pub fn html(body: impl Into<String>) -> Self {
195 let text = body.into();
196 Self {
197 status: StatusCode::OK,
198 headers: vec![("content-type".into(), "text/html; charset=utf-8".into())],
199 body: Bytes::from(text),
200 }
201 }
202
203 pub fn json_raw(body: impl Into<String>) -> Self {
204 let text = body.into();
205 Self {
206 status: StatusCode::OK,
207 headers: vec![("content-type".into(), "application/json".into())],
208 body: Bytes::from(text),
209 }
210 }
211
212 pub fn redirect(to: impl Into<String>) -> Self {
213 let url = to.into();
214 Self {
215 status: StatusCode::SEE_OTHER,
216 headers: vec![("location".into(), url)],
217 body: Bytes::new(),
218 }
219 }
220
221 pub fn text(body: impl Into<String>) -> Self {
222 let text = body.into();
223 Self {
224 status: StatusCode::OK,
225 headers: vec![("content-type".into(), "text/plain; charset=utf-8".into())],
226 body: Bytes::from(text),
227 }
228 }
229
230 pub fn with_header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
231 self.headers.push((name.into(), value.into()));
232 self
233 }
234
235 pub fn with_status(mut self, status: StatusCode) -> Self {
236 self.status = status;
237 self
238 }
239}
240
241pub(crate) fn response_from_error(err: &Error) -> Response {
242 let status = StatusCode::from_u16(err.status()).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
243 let body = err.client_message().to_string();
244 Response {
245 status,
246 headers: vec![("content-type".into(), "text/plain; charset=utf-8".into())],
247 body: Bytes::from(body),
248 }
249}