1use crate::stream::{Protocol};
2use crate::request::{Request};
3use chrono::{DateTime, Duration as dur, Utc};
4use json::{object, JsonValue};
5use log::{error, info};
6use std::path::{Path, PathBuf};
7use std::{fs, io, thread};
8use std::io::{Error};
9use hpack::Encoder;
10use crate::{ContentType, Encoding, Handler, HttpError, Method, Upgrade};
11use crate::stream::Protocol::HTTP2;
12use crate::websocket::Websocket;
13const FLAG_END_STREAM: u8 = 0x01;
14const FLAG_END_HEADERS: u8 = 0x04;
15#[derive(Clone, Debug)]
17pub struct Response {
18 pub request: Request,
19 pub status: Status,
20 pub headers: JsonValue,
21 pub cookies: JsonValue,
22 pub body: Vec<u8>,
24 pub stream_id: u32,
26 pub key: String,
28 pub version: String,
30 pub factory: fn(out: Websocket) -> Box<dyn Handler>,
31 pub allow_origins: Vec<&'static str>,
33 pub allow_methods: Vec<&'static str>,
35 pub allow_headers: Vec<&'static str>,
37 pub content_type: ContentType,
39}
40impl Response {
41 pub fn new(request: &Request, factory: fn(out: Websocket) -> Box<dyn Handler>) -> Self {
42 Self {
43 request: request.clone(),
44 status: Status::default(),
45 headers: object! {},
46 cookies: object! {},
47 body: vec![],
48 stream_id: 0,
49 key: String::new(),
50 version: String::new(),
51 factory,
52 allow_origins: vec![],
53 allow_methods: vec![],
54 allow_headers: vec![],
55 content_type: ContentType::Other(String::new()),
56 }
57 }
58 pub fn handle(mut self) -> io::Result<()> {
59 match self.request.upgrade {
60 Upgrade::Websocket => {
61 self.handle_protocol_ws()?;
62 return Ok(());
63 }
64 Upgrade::Http | Upgrade::Other(_) => {}
65 Upgrade::H2c => {
66 let _ = self.handle_protocol_h2c();
67 }
68 }
69
70 match self.request.protocol {
71 Protocol::HTTP1_0 => self.handle_protocol_http0()?,
72 Protocol::HTTP1_1 => self.handle_protocol_http1()?,
73 Protocol::HTTP2 => self.handle_protocol_http2()?,
74 Protocol::HTTP3 | Protocol::Other(_) => {}
75 }
76 Ok(())
77 }
78 fn handle_protocol_http0(&mut self) -> io::Result<()> {
79 let websocket = Websocket::http(self.request.clone(), self.clone());
80 let mut factory = (self.factory)(websocket);
81 match self.request.method {
82 Method::OPTIONS => {
83 factory.on_options(self);
84 match self.on_options() {
85 Ok(()) => {
86 match self.status(200).send() {
87 Ok(()) => {}
88 Err(e) => return Err(Error::other(format!("1004: {} {} {}", self.request.uri.path, e.code, e.body))),
89 }
90 }
91 Err(e) => return {
92 self.status(e.code).txt(e.body.as_str()).send().unwrap();
93 Ok(())
94 }
95 }
96 }
97 Method::GET => {
98 if let Ok(e) = self.read_resource() {
99 if self.request.header.has_key("range") {
100 return match self.status(206).range(&e).send() {
101 Ok(()) => Ok(()),
102 Err(e) => Err(Error::other(format!("1003: {} {} {}", self.request.uri.path, e.code, e.body))),
103 };
104 }
105 return match self.status(200).file(&e).send() {
106 Ok(_) => Ok(()),
107 Err(e) => Err(Error::other(format!("1003: {} {} {}", self.request.uri.path, e.code, e.body))),
108 };
109 }
110 factory.on_request(self.request.clone(), self);
111 factory.on_response(self);
112 match self.send() {
113 Ok(()) => {}
114 Err(e) => return Err(Error::other(format!("1002: {} {} {}", self.request.uri.path, e.code, e.body))),
115 }
116 }
117 _ => {
118 factory.on_request(self.request.clone(), self);
119 factory.on_response(self);
120 match self.send() {
121 Ok(_) => {}
122 Err(e) => return Err(Error::other(format!("1001: {} {}", e.code, e.body))),
123 }
124 }
125 }
126 Ok(())
127 }
128 fn handle_protocol_http1(&mut self) -> io::Result<()> {
129 self.handle_protocol_http0()
130 }
131 fn handle_protocol_http2(&mut self) -> io::Result<()> {
132 let websocket = Websocket::http(self.request.clone(), self.clone());
133 let mut factory = (self.factory)(websocket);
134
135 match self.request.method {
136 Method::OPTIONS => {
137 factory.on_options(self);
138 match self.send() {
139 Ok(_) => {}
140 Err(e) => return Err(Error::other(format!("2001: {} {}", e.code, e.body))),
141 };
142 }
143 Method::GET => {
144 if let Ok(e) = self.read_resource() {
145 return match self.status(200).file(&e).send() {
146 Ok(_) => Ok(()),
147 Err(e) => Err(Error::other(e.body)),
148 };
149 }
150 factory.on_request(self.request.clone(), self);
151 factory.on_response(self);
152 match self.send() {
153 Ok(()) => {}
154 Err(e) => return Err(Error::other(format!("2002: {} {}", e.code, e.body))),
155 }
156 }
157 _ => {
158 factory.on_request(self.request.clone(), self);
159 factory.on_response(self);
160 match self.send() {
161 Ok(_) => {}
162 Err(e) => return Err(Error::other(format!("2003: {} {}", e.code, e.body))),
163 }
164 }
165 }
166 Ok(())
167 }
168 fn handle_protocol_ws(&mut self) -> io::Result<()> {
169 let mut websocket = Websocket::new(self.request.clone(), self.clone());
170 let _ = websocket.handle();
171 Ok(())
172 }
173 fn handle_protocol_h2c(&mut self) -> Result<(), HttpError> {
174 self.header("Upgrade", "h2c");
175 self.header("Connection", "Upgrade");
176 match self.status(101).send() {
177 Ok(()) => self.headers.clear(),
178 Err(e) => return Err(e)
179 };
180 self.request.protocol=HTTP2;
181 self.request.scheme.lock().unwrap().http2_send_server_settings()?;
182 let mut data = vec![];
183 self.request.scheme.lock().unwrap().read(&mut data)?;
184
185 let t = b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n";
186 if let Some(pos) = data.windows(t.len()).position(|window| window == t) {
187 let _ = data.drain(..pos).collect::<Vec<u8>>();
188 data.drain(..t.len());
189 } else {
190 return Err(HttpError::new(400, "请求行错误"));
191 }
192 let (_payload, _frame_type, flags, _stream_id) = self.request.scheme.lock().unwrap().http2_packet(&mut data)?;
193 if flags & 0x01 == 0 {
194 self.request.scheme.lock().unwrap().http2_settings_ack()?;
195 }
196 let (_payload, _frame_type, _flags, _stream_id) = self.request.scheme.lock().unwrap().http2_packet(&mut data)?;
197 let (payload, _frame_type, _flags, _stream_id) = self.request.scheme.lock().unwrap().http2_packet(&mut data)?;
198 if payload.len() == 4 {
199 let raw = u32::from_be_bytes(payload.clone().try_into().unwrap());
200 let increment = raw & 0x7FFF_FFFF; if self.request.config.debug {
202 info!("WindowUpdate: increment = {} {:?}", increment,payload);
203 }
204 } else {
205 return Err(HttpError::new(400, format!("Invalid WindowUpdate frame length: {}", payload.len()).as_str()));
206 }
207 Ok(())
208 }
209 fn read_resource(&mut self) -> io::Result<PathBuf> {
211 if self.request.uri.path != "/" {
212 let file = self.request.config.root_path.join(self.request.config.public.clone()).join(self.request.uri.path.trim_start_matches('/'));
213 if file.is_file() {
214 return Ok(file);
215 }
216 }
217 if self.request.uri.path == "/" {
218 let file = self.request.config.root_path.join("webpage").join(self.request.config.webpage.clone()).join("index.html");
219 if file.is_file() {
220 return Ok(file);
221 }
222 } else {
223 let file = self.request.config.root_path.join("webpage").join(self.request.config.webpage.clone()).join(self.request.uri.path.trim_start_matches('/'));
224 if file.is_file() {
225 return Ok(file);
226 }
227 }
228 Err(Error::other("Not a file"))
229 }
230 pub fn status(&mut self, code: u16) -> &mut Self {
231 self.status.set_code(code);
232 self
233 }
234 pub fn location(&mut self, uri: &str) -> &mut Self {
236 self.header("Location", uri);
237 self
238 }
239 pub fn set_host(&mut self, host: &str) -> &mut Self {
241 self.header("Host", host);
242 self
243 }
244
245 pub fn header(&mut self, key: &str, value: &str) -> &mut Self {
246 self.headers[key] = value.into();
247 self
248 }
249 pub fn cookie(&mut self, key: &str, value: &str) -> &mut Self {
250 self.cookies[key] = value.into();
251 self
252 }
253 fn get_date(&self, s: i64) -> String {
254 let utc: DateTime<Utc> = Utc::now();
255 let future = utc + dur::seconds(s); future.format("%a, %d %b %Y %H:%M:%S GMT").to_string()
257 }
258 pub fn html(&mut self, value: &str) -> &mut Self {
260 if self.request.config.charset.is_empty() {
261 self.header("Content-Type", format!("{};", Extension::form("html").as_str()).as_str());
262 } else {
263 self.header("Content-Type", format!("{}; charset={}", Extension::form("html").as_str(), self.request.config.charset).as_str());
264 }
265 self.content_type = ContentType::Html;
266 self.body = value.as_bytes().to_vec();
267 self
268 }
269 pub fn txt(&mut self, value: &str) -> &mut Self {
271 if self.request.config.charset.is_empty() {
272 self.header("Content-Type", Extension::form("txt").as_str().to_string().as_str());
273 } else {
274 self.header("Content-Type", format!("{}; charset={}", Extension::form("txt").as_str(), self.request.config.charset).as_str());
275 }
276 self.content_type = ContentType::Text;
277 self.body = value.as_bytes().to_vec();
278 self
279 }
280 pub fn json(&mut self, value: JsonValue) -> &mut Self {
282 if self.request.config.charset.is_empty() {
283 self.header("Content-Type", Extension::form("json").as_str().to_string().as_str());
284 } else {
285 self.header("Content-Type", format!("{}; charset={}", Extension::form("json").as_str(), self.request.config.charset).as_str());
286 }
287 self.content_type = ContentType::Json;
288 self.body = value.to_string().into_bytes();
289 self
290 }
291 pub fn download(&mut self, filename: &Path) -> &mut Self {
300 let Ok(file) = fs::read(filename) else {
301 self.status(404);
302 return self;
303 };
304 let extension = filename.extension().unwrap().to_str().unwrap().to_lowercase();
305
306 if self.request.config.charset.is_empty() {
307 self.header("Content-Type", Extension::form(extension.as_str()).as_str().to_string().as_str());
308 } else {
309 self.header("Content-Type", format!("{}; charset={}", Extension::form(extension.as_str()).as_str(), self.request.config.charset).as_str());
310 }
311
312 let encoded_file_name = br_crypto::encoding::urlencoding_encode(filename.file_name().unwrap().to_str().unwrap());
313 self.header("Content-Disposition", format!(r"attachment; filename={encoded_file_name}").as_str());
314 self.header("Cache-Control", "no-cache");
315 self.header("ETag", br_crypto::md5::encrypt_hex(&file).as_str());
316 self.body = file;
317 self
318 }
319 pub fn range(&mut self, filename: &Path) -> &mut Self {
321 let Ok(file) = fs::read(filename) else {
322 self.status(404);
323 return self;
324 };
325 let range = self.request.header["range"].to_string();
326 let range = range.trim_start_matches("bytes=");
327 let range = range.split("-").collect::<Vec<&str>>();
328 let range_start = range[0].parse::<usize>().unwrap();
329 let range_end = range[1].parse::<usize>().unwrap();
330
331 if file.len() < range_end {
332 self.status(416);
333 self.header("Content-Range", format!("bytes */{}", file.len()).as_str());
334 return self;
335 }
336
337 let extension = filename.extension().unwrap().to_str().unwrap().to_lowercase();
338
339 if self.request.config.charset.is_empty() {
340 self.header("Content-Type", Extension::form(extension.as_str()).as_str().to_string().as_str());
341 } else {
342 self.header("Content-Type", format!("{}; charset={}", Extension::form(extension.as_str()).as_str(), self.request.config.charset).as_str());
343 }
344
345 self.header("Accept-Ranges", "bytes");
346 self.header("content-length", (range_end - range_start + 1).to_string().as_str());
347 self.header("Content-Range", format!("bytes {}-{}/{}", range_start, range_end, file.len()).as_str());
348 self.body = file[range_start..=range_end].to_vec();
349 self
350 }
351 pub fn file(&mut self, filename: &Path) -> &mut Self {
358 let Ok(file) = fs::read(filename) else {
359 self.status(404);
360 return self;
361 };
362
363 self.header("Access-Control-Expose-Headers", "Content-Disposition");
364 let extension = match filename.extension() {
365 None => String::new(),
366 Some(e) => e.to_str().unwrap().to_lowercase(),
367 };
368 if self.request.config.charset.is_empty() {
369 self.header("Content-Type", Extension::form(extension.as_str()).as_str().to_string().as_str());
370 } else {
371 self.header("Content-Type", format!("{}; charset={}", Extension::form(extension.as_str()).as_str(), self.request.config.charset).as_str());
372 }
373
374 self.header("Content-Disposition", format!(r#"inline; filename="{}""#, filename.file_name().unwrap().to_str().unwrap()).as_str());
375
376 self.header("Accept-Ranges", "bytes");
377
378 self.header("Cache-Control", format!("public, max-age={}", 81400).as_str());
379 self.header("Expires", &self.clone().get_date(81400));
380 self.body = file;
381 self
382 }
383 pub fn send(&mut self) -> Result<(), HttpError> {
389 match &self.request.protocol {
390 Protocol::HTTP1_0 | Protocol::HTTP1_1 => Ok(self.send_http1()?),
391 Protocol::HTTP2 => Ok(self.send_http2()?),
392 Protocol::HTTP3 => {
393 error!("Other1:{:?} {:?}", thread::current().id(),self.request);
394 Err(HttpError::new(500, "暂未实现HTTP3"))
395 }
396 Protocol::Other(e) => {
397 error!("Other:{:?} {:?}", thread::current().id(),self.request);
398 Err(HttpError::new(500, format!("暂未实现Other: {} {} {:?}", e, self.request.uri.path, thread::current().id()).as_str()))
399 }
400 }
401 }
402 fn send_http1(&mut self) -> Result<(), HttpError> {
403 let mut header = vec![];
404 header.push(format!("{} {} {}", self.request.protocol.str(), self.status.code, self.status.reason));
405 self.header("Date", &self.get_date(0));
406
407 match self.request.method {
408 Method::HEAD => {
409 self.header("Content-Length", self.body.len().to_string().as_str());
410 self.body = vec![];
411 }
412 Method::OPTIONS => {
413 self.body = vec![];
415 }
416 _ => {
417 match self.request.accept_encoding {
418 Encoding::Gzip => {
419 self.header("Content-Encoding", self.request.accept_encoding.clone().str());
420 if let Ok(e) = self.request.accept_encoding.clone().compress(&self.body.clone()) { self.body = e };
421 self.header("Content-Length", self.body.len().to_string().as_str());
422 }
423 _ => { self.header("Content-Length", self.body.len().to_string().as_str()); }
424 }
425 }
426 };
427
428 for (key, value) in self.headers.entries() {
429 header.push(format!("{key}: {value}"));
430 }
431
432 for (key, value) in self.cookies.entries() {
433 header.push(format!("Set-Cookie: {key}={value}; Path=/; HttpOnly; SameSite=Lax"));
434 }
435
436 if self.request.config.debug {
437 info!("\r\n=================响应信息 {:?}=================\r\n{}\r\n===========================================",thread::current().id(),header.join("\r\n"));
438 match self.request.accept_encoding {
439 Encoding::Gzip => {}
440 _ => {
441 match self.content_type {
442 ContentType::Text | ContentType::Html | ContentType::Json | ContentType::FormUrlencoded => {
443 info!("\r\n=================响应体 {:?}=================\r\n{}\r\n===========================================",thread::current().id(),String::from_utf8_lossy(self.body.as_slice()));
444 }
445 _ => {}
446 };
447 }
448 }
449 }
450 let mut headers = format!("{}\r\n\r\n", header.join("\r\n")).into_bytes();
451 headers.extend(self.body.clone());
452 self.request.scheme.lock().unwrap().write_all(headers.as_slice())?;
453 Ok(())
454 }
455 fn send_http2(&mut self) -> Result<(), HttpError> {
456
457 let max_frame_size: usize = 16_384;
458 self.stream_id += 1;
459 let header_frames = self.http2_header(self.stream_id, max_frame_size);
461 let data_frames = self.http2_body(self.stream_id, true, max_frame_size);
462
463 let mut writer = self.request.scheme.lock().unwrap();
465 for f in header_frames.clone() { writer.write_all(&f)?; }
466 for f in data_frames.clone() { writer.write_all(&f)?; }
467 Ok(())
468 }
469
470 fn http2_header(&mut self, stream_id: u32, max_frame_size: usize) -> Vec<Vec<u8>> {
471 let mut headers: Vec<(Vec<u8>, Vec<u8>)> = vec![
472 (b":status".to_vec(), self.status.code.to_string().into_bytes()),
473 (b"date".to_vec(), self.get_date(0).into_bytes()),
474 ];
475
476 match self.request.method {
477 Method::HEAD => {
478 self.header("content-length", self.body.len().to_string().as_str());
479 self.body.clear(); }
481 Method::OPTIONS => {
482 self.body.clear();
483 self.header("content-length", "0");
484 }
485 _ => {
486 self.header("content-length", self.body.len().to_string().as_str());
487 }
488 }
489
490 headers.extend(
491 self.headers.entries().map(|(k, v)| (k.to_string().to_lowercase().into_bytes(), v.to_string().into_bytes()))
492 );
493 headers.extend(
494 self.cookies.entries().map(|(k, v)| (b"set-cookie".to_vec(), format!("{k}={v}; Path=/; HttpOnly; SameSite=Lax").into_bytes()))
495 );
496
497 if self.request.config.debug {
498 let dbg = headers.iter().map(|(n, v)| {
499 format!("{}: {}", String::from_utf8_lossy(n), String::from_utf8_lossy(v))
500 }).collect::<Vec<_>>().join("\r\n");
501 info!("\n=================响应信息 {:?}=================\n{}\n===========================================",
502 std::thread::current().id(), dbg);
503 }
504
505 let mut encoder = Encoder::new();
506 let block = encoder.encode(headers.iter().map(|h| (&h.0[..], &h.1[..])));
508
509 let end_stream = self.body.is_empty();
510 let mut frames = Vec::new();
511 let mut remaining = block.as_slice();
512 let mut first = true;
513
514 while !remaining.is_empty() {
515 let take = remaining.len().min(max_frame_size);
516 let (chunk, rest) = remaining.split_at(take);
517 remaining = rest;
518
519 let is_last = remaining.is_empty();
520 let mut flags = 0u8;
521 if is_last { flags |= FLAG_END_HEADERS; }
522 if is_last && end_stream { flags |= FLAG_END_STREAM; }
523
524 let mut f = Vec::with_capacity(9 + chunk.len());
526 let len = chunk.len();
527 f.push(((len >> 16) & 0xFF) as u8);
528 f.push(((len >> 8) & 0xFF) as u8);
529 f.push((len & 0xFF) as u8);
530 f.push(if first { 0x01 } else { 0x09 }); f.push(flags);
532 f.extend_from_slice(&(stream_id & 0x7FFF_FFFF).to_be_bytes());
533 f.extend_from_slice(chunk);
534
535 frames.push(f);
536 first = false;
537 }
538
539 if frames.is_empty() {
541 let mut f = vec![0, 0, 0, 0x01, FLAG_END_HEADERS | if end_stream { FLAG_END_STREAM } else { 0 }, 0, 0, 0, 0];
542 f[5..9].copy_from_slice(&(stream_id & 0x7FFF_FFFF).to_be_bytes());
543 frames.push(f);
544 }
545
546 frames
547 }
548 fn http2_body(&mut self, stream_id: u32, end_stream: bool, max_frame_size: usize) -> Vec<Vec<u8>> {
549 if self.body.is_empty() {
550 return Vec::new();
551 }
552 let mut frames = Vec::new();
553 let mut off = 0usize;
554 let total = self.body.len();
555
556 while off < total {
557 let take = (total - off).min(max_frame_size);
558 let chunk = &self.body[off..off + take];
559 off += take;
560
561 let last = off == total;
562 frames.push(self.build_data_frame(stream_id, chunk, last && end_stream));
563 }
564 frames
565 }
566 fn build_data_frame(&self, stream_id: u32, payload: &[u8], end_stream: bool) -> Vec<u8> {
567 let len = payload.len();
568 let mut f = Vec::with_capacity(9 + len);
569 f.push(((len >> 16) & 0xFF) as u8);
570 f.push(((len >> 8) & 0xFF) as u8);
571 f.push((len & 0xFF) as u8);
572 f.push(0x00); f.push(if end_stream { FLAG_END_STREAM } else { 0 });
574 f.extend_from_slice(&(stream_id & 0x7FFF_FFFF).to_be_bytes());
575 if !payload.is_empty() { f.extend_from_slice(payload); }
576 f
577 }
578 fn on_options(&mut self) -> Result<(), HttpError> {
579 if self.allow_origins.is_empty() {
580 self.header("Access-Control-Allow-Origin", "*");
581 } else if self.request.header.has_key("origin") {
582 if self.allow_origins.contains(&self.request.origin.as_str()) {
583 self.header("Access-Control-Allow-Origin", self.request.origin.to_string().as_str());
584 } else {
585 return Err(HttpError::new(403, "Origin not allowed"));
586 }
587 } else {
588 return Err(HttpError::new(403, "Origin not allowed"));
589 }
590
591 if self.allow_headers.is_empty() {
592 if !self.request.header.has_key("access-control-request-headers") {
593 return Err(HttpError::new(403, "headers not allowed"));
594 }
595 self.header("Access-Control-Allow-Headers", self.request.header["access-control-request-headers"].to_string().as_str());
596 } else if !self.request.header.has_key("access-control-request-headers") {
597 let headers = self.allow_headers.join(",");
598 self.header("Access-Control-Allow-Headers", headers.to_string().as_str());
599 } else {
600 let headers = self.allow_headers.join(",");
601 self.header("Access-Control-Allow-Headers", format!("{},{}", self.request.header["access-control-request-headers"], headers).as_str());
602 }
603
604 if self.allow_methods.is_empty() {
605 if !self.request.header.has_key("access-control-request-method") {
606 return Err(HttpError::new(403, "methods not allowed"));
607 }
608 self.header("Access-Control-Allow-Methods", self.request.header["access-control-request-method"].to_string().as_str());
609 } else {
610 let methods = self.allow_methods.join(",");
611 self.header("Access-Control-Allow-Methods", methods.to_string().as_str());
612 }
613 self.header("Vary", "Origin, Access-Control-Request-Method, Access-Control-Request-Headers");
614 Ok(())
615 }
616}
617#[derive(Clone, Debug)]
618pub struct Status {
619 pub code: u16,
620 reason: String,
621}
622impl Status {
623 pub fn set_code(&mut self, code: u16) {
624 self.code = code;
625 self.reason = match code {
626 100 => "Continue", 101 => "Switching Protocols", 102 => "Processing",
629 103 => "Early Hints", 200 => "OK", 201 => "Created", 202 => "Accepted", 204 => "No Content", 206 => "Partial Content", 301 => "Moved Permanently", 302 => "Found", 303 => "See Other", 304 => "Not Modified", 307 => "Temporary Redirect", 308 => "Permanent Redirect", 400 => "Bad Request", 401 => "Unauthorized", 403 => "Forbidden",
645 404 => "Not Found", 405 => "Method Not Allowed", 411 => "Length Required", 413 => "Payload Too Large", 414 => "URI Too Long", 416 => "Range Not Satisfiable",
651 429 => "Too Many Requests", 431 => "Request Header Fields Too Large", 500 => "Internal Server Error", 501 => "Not Implemented", 502 => "Bad Gateway", 503 => "Service Unavailable", 504 => "Gateway Time-out", 505 => "HTTP Version Not Supported", _ => "",
661 }.to_string();
662 }
663}
664impl Default for Status {
665 fn default() -> Self {
666 Self {
667 code: 200,
668 reason: "OK".to_string(),
669 }
670 }
671}
672
673enum Extension {}
675impl Extension {
676 pub fn form(extension: &str) -> String {
677 match extension.to_lowercase().as_str() {
678 "html" => "text/html",
679 "css" => "text/css",
680 "js" => "application/javascript",
681 "json" => "application/json",
682 "png" => "image/png",
683
684 "mp4" => "video/mp4",
685 "jpg" | "jpeg" => "image/jpeg",
686 "gif" => "image/gif",
687 "txt" => "text/plain",
688 "pdf" => "application/pdf",
689 "svg" => "image/svg+xml",
690 "woff" => "application/font-woff",
691 "woff2" => "application/font-woff2",
692 "xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
693 _ => "application/octet-stream",
694 }.to_string()
695 }
696}
697
698