hyper_staticfile_jsutf8/
resolve.rs

1use crate::util::{open_with_metadata, RequestedPath};
2use http::{Method, Request};
3use mime_guess::{Mime, MimeGuess};
4use std::fs::Metadata;
5use std::io::{Error as IoError, ErrorKind as IoErrorKind};
6use std::path::PathBuf;
7use std::str::FromStr;
8use tokio::fs::File;
9
10/// The result of `resolve`.
11///
12/// Covers all the possible 'normal' scenarios encountered when serving static files.
13#[derive(Debug)]
14pub enum ResolveResult {
15    /// The request was not `GET` or `HEAD` request,
16    MethodNotMatched,
17    /// The requested file does not exist.
18    NotFound,
19    /// The requested file could not be accessed.
20    PermissionDenied,
21    /// A directory was requested as a file.
22    IsDirectory,
23    /// The requested file was found.
24    Found(File, Metadata, Mime),
25}
26
27/// Some IO errors are expected when serving files, and mapped to a regular result here.
28fn map_open_err(err: IoError) -> Result<ResolveResult, IoError> {
29    match err.kind() {
30        IoErrorKind::NotFound => Ok(ResolveResult::NotFound),
31        IoErrorKind::PermissionDenied => Ok(ResolveResult::PermissionDenied),
32        _ => Err(err),
33    }
34}
35
36/// Resolve the request by trying to find the file in the given root.
37///
38/// This root may be absolute or relative. The request is mapped onto the filesystem by appending
39/// its URL path to the root path. If the filesystem path corresponds to a regular file, the
40/// service will attempt to serve it. Otherwise, if the path corresponds to a directory containing
41/// an `index.html`, the service will attempt to serve that instead.
42///
43/// The returned future may error for unexpected IO errors, passing on the `std::io::Error`.
44/// Certain expected IO errors are handled, though, and simply reflected in the result. These are
45/// `NotFound` and `PermissionDenied`.
46pub async fn resolve<B>(
47    root: impl Into<PathBuf>,
48    req: &Request<B>,
49) -> Result<ResolveResult, IoError> {
50    // Handle only `GET`/`HEAD` and absolute paths.
51    match *req.method() {
52        Method::HEAD | Method::GET => {}
53        _ => {
54            return Ok(ResolveResult::MethodNotMatched);
55        }
56    }
57
58    resolve_path(root, req.uri().path()).await
59}
60
61/// Resolve the request path by trying to find the file in the given root.
62///
63/// This root may be absolute or relative. The request path is mapped onto the filesystem by
64/// appending it to the root path. If the filesystem path corresponds to a regular file, the
65/// service will attempt to serve it. Otherwise, if the path corresponds to a directory containing
66/// an `index.html`, the service will attempt to serve that instead.
67///
68/// The returned future may error for unexpected IO errors, passing on the `std::io::Error`.
69/// Certain expected IO errors are handled, though, and simply reflected in the result. These are
70/// `NotFound` and `PermissionDenied`.
71///
72/// Note that, unlike `resolve`, it is up to the caller to check the request method.
73pub async fn resolve_path(
74    root: impl Into<PathBuf>,
75    request_path: &str,
76) -> Result<ResolveResult, IoError> {
77    let RequestedPath {
78        sanitized,
79        is_dir_request,
80    } = RequestedPath::resolve(request_path);
81
82    let mut full_path = root.into();
83    full_path.extend(&sanitized);
84
85    let (file, metadata) = match open_with_metadata(&full_path).await {
86        Ok(pair) => pair,
87        Err(err) => return map_open_err(err),
88    };
89
90    // The resolved `full_path` doesn't contain the trailing slash anymore, so we may
91    // have opened a file for a directory request, which we treat as 'not found'.
92    if is_dir_request && !metadata.is_dir() {
93        return Ok(ResolveResult::NotFound);
94    }
95
96    // We may have opened a directory for a file request, in which case we redirect.
97    if !is_dir_request && metadata.is_dir() {
98        return Ok(ResolveResult::IsDirectory);
99    }
100
101    // If not a directory, serve this file.
102    if !is_dir_request {
103        let mime = set_charset(MimeGuess::from_path(&full_path).first_or_octet_stream());
104        return Ok(ResolveResult::Found(file, metadata, mime));
105    }
106
107    // Resolve the directory index.
108    full_path.push("index.html");
109    let (file, metadata) = match open_with_metadata(&full_path).await {
110        Ok(pair) => pair,
111        Err(err) => return map_open_err(err),
112    };
113
114    // The directory index cannot itself be a directory.
115    if metadata.is_dir() {
116        return Ok(ResolveResult::NotFound);
117    }
118
119    // Serve this file.
120    let mime = MimeGuess::from_path(full_path).first_or_octet_stream();
121    Ok(ResolveResult::Found(file, metadata, set_charset(mime)))
122}
123
124// 判断mime是否是application/javascript, 如果是则将mime设置为 application/javascript; charset=utf-8
125// 如果不是则直接返回mime
126fn set_charset(mime: Mime) -> Mime {
127    let javascript_mime: Mime = "application/javascript".parse().unwrap();
128    if mime == javascript_mime {
129        return Mime::from_str("application/javascript; charset=utf-8").unwrap();
130    }
131    mime
132}