1use compmd_pack::FilePath;
7use http::header::HeaderValue;
8use http::{Request, Response};
9
10use crate::bundle::Bundle;
11use crate::headers::{refusal_headers, served_headers};
12use crate::refusal::Refusal;
13use crate::route::{Route, route};
14use crate::store::Store;
15
16pub fn respond<B>(bundle: &Bundle, store: &dyn Store, request: &Request<B>) -> Response<Vec<u8>> {
22 let hash = bundle.manifest().frames.hash.as_str();
23 let found = match route(request.method(), request.uri().path(), hash) {
24 Route::Frame(path) => bundle.frame_file(&path).map(|body| (body, path)),
25 Route::Pack(place) => bundle
26 .pack_file(&place)
27 .or_else(|| store.file(&place))
28 .map(|body| (body, place.path)),
29 Route::Refused(refusal) => return refused(refusal),
30 };
31 found.map_or_else(
32 || refused(Refusal::NOT_SERVED),
33 |(body, path)| served(&path, body),
34 )
35}
36
37fn served(path: &FilePath, body: Vec<u8>) -> Response<Vec<u8>> {
39 with_headers(Response::new(body), served_headers(path.as_str()))
40}
41
42fn refused(refusal: Refusal) -> Response<Vec<u8>> {
44 let mut response = Response::new(refusal.why.as_bytes().to_vec());
45 *response.status_mut() = refusal.status;
46 with_headers(response, refusal_headers())
47}
48
49fn with_headers(
51 mut response: Response<Vec<u8>>,
52 headers: impl IntoIterator<Item = (&'static str, &'static str)>,
53) -> Response<Vec<u8>> {
54 for (name, value) in headers {
55 response
56 .headers_mut()
57 .insert(name, HeaderValue::from_static(value));
58 }
59 response
60}
61
62#[cfg(test)]
63mod tests;