Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: dev server support "publicPath" #1398

Merged
merged 4 commits into from
Jul 22, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 15 additions & 3 deletions crates/mako/src/dev/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ use {hyper, hyper_staticfile, hyper_tungstenite, open};

use crate::compiler::{Compiler, Context};
use crate::plugin::{PluginGenerateEndParams, PluginGenerateStats};
use crate::utils::tokio_runtime;
use crate::utils::{process_req_url, tokio_runtime};

pub struct DevServer {
root: PathBuf,
Expand Down Expand Up @@ -124,15 +124,27 @@ impl DevServer {
staticfile: hyper_staticfile::Static,
txws: broadcast::Sender<WsMessage>,
) -> Result<hyper::Response<Body>> {
let path = req.uri().path();
let mut path = req.uri().path().to_string();
let public_path = &context.config.public_path;
if !public_path.is_empty() {
path = match process_req_url(public_path, &path) {
Ok(p) => p,
Err(_) => {
return Ok(hyper::Response::builder()
.status(hyper::StatusCode::BAD_REQUEST)
.body(hyper::Body::from("Bad Request"))
.unwrap());
}
};
}
let path_without_slash_start = path.trim_start_matches('/');
let not_found_response = || {
hyper::Response::builder()
.status(hyper::StatusCode::NOT_FOUND)
.body(hyper::Body::empty())
.unwrap()
};
match path {
match path.as_str() {
"/__/hmr-ws" => {
if hyper_tungstenite::is_upgrade_request(&req) {
debug!("new websocket connection");
Expand Down
45 changes: 45 additions & 0 deletions crates/mako/src/utils/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,48 @@ impl ParseRegex for Option<String> {
})
}
}

pub fn process_req_url(public_path: &str, req_url: &str) -> Result<String> {
let public_path = format!("/{}/", public_path.trim_matches('/'));
if req_url.starts_with(&public_path) {
return Ok(req_url[public_path.len() - 1..].to_string());
}
Ok(req_url.to_string())
Comment on lines +36 to +41
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

建议改进: 优化字符串处理逻辑

目前的逻辑虽然正确,但可以使用标准库提供的方法来简化字符串的处理。例如,可以使用 strip_prefixstrip_suffix 方法来处理路径。

pub fn process_req_url(public_path: &str, req_url: &str) -> Result<String> {
    let public_path = format!("/{}/", public_path.trim_matches('/'));
    if req_url.starts_with(&public_path) {
        return Ok(req_url[public_path.len() - 1..].to_string());
    }
    Ok(req_url.to_string())
}

}

#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_process_req_url() {
assert_eq!(
process_req_url("/public/", "/public/index.html").unwrap(),
"/index.html"
);
assert_eq!(
process_req_url("public/", "/public/index.html").unwrap(),
"/index.html"
);
assert_eq!(
process_req_url("/public/foo/", "/public/foo/index.html").unwrap(),
"/index.html"
);
assert_eq!(
process_req_url("public/foo/", "/public/foo/index.html").unwrap(),
"/index.html"
);
assert_eq!(process_req_url("/", "/index.html").unwrap(), "/index.html");
assert_eq!(
process_req_url("/#/", "/#/index.html").unwrap(),
"/index.html"
);
assert_eq!(
process_req_url("/公共路径/", "/公共路径/index.html").unwrap(),
"/index.html"
);
assert_eq!(
process_req_url("公共路径/", "/公共路径/index.html").unwrap(),
"/index.html"
);
}
}
16 changes: 16 additions & 0 deletions packages/bundler-mako/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,22 @@ exports.dev = async function (opts) {

const outputPath = path.resolve(opts.cwd, opts.config.outputPath || 'dist');

function processReqURL(publicPath, reqURL) {
if (!publicPath.startsWith('/')) {
publicPath = '/' + publicPath;
}
if (reqURL.startsWith(publicPath)) {
return reqURL.slice(publicPath.length - 1);
} else {
return reqURL;
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

建议改进: 优化 processReqURL 函数

目前的逻辑可以进一步简化和优化,以提高代码的可读性和处理边界情况的能力。

function processReqURL(publicPath, reqURL) {
  if (!publicPath.startsWith('/')) {
    publicPath = '/' + publicPath;
  }
  publicPath = publicPath.replace(/\/+$/, '') + '/';
  if (reqURL.startsWith(publicPath)) {
    return reqURL.slice(publicPath.length - 1);
  }
  return reqURL;
}

这样可以确保 publicPath 总是以一个斜杠开头和结尾,并且处理了多个结尾斜杠的情况。

if (opts.config.publicPath) {
app.use((req, res, next) => {
req.url = processReqURL(opts.config.publicPath, req.url);
next();
});
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

建议改进: 提高中间件的可读性

目前的中间件逻辑可以通过解构 opts.config 来提高可读性。

const { publicPath } = opts.config;
if (publicPath) {
  app.use((req, res, next) => {
    req.url = processReqURL(publicPath, req.url);
    next();
  });
}

这样可以使代码更加简洁和易读。

}
// serve dist files
app.use(express.static(outputPath));

Expand Down
Loading