hyper_staticfile/
response_builder.rs1use http::{
2 header, response::Builder as HttpResponseBuilder, HeaderMap, Method, Request, Response, Result,
3 StatusCode, Uri,
4};
5
6use crate::{resolve::ResolveResult, util::FileResponseBuilder, vfs::IntoFileAccess, Body};
7
8#[derive(Clone, Debug, Default)]
14pub struct ResponseBuilder<'a> {
15 pub path: &'a str,
17 pub query: Option<&'a str>,
19 pub file_response_builder: FileResponseBuilder,
21}
22
23impl<'a> ResponseBuilder<'a> {
24 pub fn new() -> Self {
26 Self::default()
27 }
28
29 pub fn request<B>(&mut self, req: &'a Request<B>) -> &mut Self {
31 self.request_parts(req.method(), req.uri(), req.headers());
32 self
33 }
34
35 pub fn request_parts(
37 &mut self,
38 method: &Method,
39 uri: &'a Uri,
40 headers: &'a HeaderMap,
41 ) -> &mut Self {
42 self.request_uri(uri);
43 self.file_response_builder.request_parts(method, headers);
44 self
45 }
46
47 pub fn request_uri(&mut self, uri: &'a Uri) -> &mut Self {
49 self.path(uri.path());
50 self.query(uri.query());
51 self
52 }
53
54 pub fn cache_headers(&mut self, value: Option<u32>) -> &mut Self {
56 self.file_response_builder.cache_headers(value);
57 self
58 }
59
60 pub fn path(&mut self, value: &'a str) -> &mut Self {
62 self.path = value;
63 self
64 }
65
66 pub fn query(&mut self, value: Option<&'a str>) -> &mut Self {
68 self.query = value;
69 self
70 }
71
72 pub fn build<F: IntoFileAccess>(
77 &self,
78 result: ResolveResult<F>,
79 ) -> Result<Response<Body<F::Output>>> {
80 match result {
81 ResolveResult::MethodNotMatched => HttpResponseBuilder::new()
82 .status(StatusCode::BAD_REQUEST)
83 .body(Body::Empty),
84 ResolveResult::NotFound => HttpResponseBuilder::new()
85 .status(StatusCode::NOT_FOUND)
86 .body(Body::Empty),
87 ResolveResult::PermissionDenied => HttpResponseBuilder::new()
88 .status(StatusCode::FORBIDDEN)
89 .body(Body::Empty),
90 ResolveResult::IsDirectory {
91 redirect_to: mut target,
92 } => {
93 if let Some(query) = self.query {
95 target.push('?');
96 target.push_str(query);
97 }
98
99 HttpResponseBuilder::new()
100 .status(StatusCode::MOVED_PERMANENTLY)
101 .header(header::LOCATION, target)
102 .body(Body::Empty)
103 }
104 ResolveResult::Found(file) => self.file_response_builder.build(file),
105 }
106 }
107}