Skip to content

Commit a03637c

Browse files
huanyu.whystephank
authored andcommitted
feat: add js response content-type charset
1 parent 26a8d04 commit a03637c

File tree

2 files changed

+29
-6
lines changed

2 files changed

+29
-6
lines changed

src/resolve.rs

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ use std::{
99

1010
use futures_util::future::BoxFuture;
1111
use http::{header, HeaderValue, Method, Request};
12-
use mime_guess::MimeGuess;
12+
use mime_guess::{mime, Mime, MimeGuess};
1313
use tokio::fs::File;
1414

1515
use crate::{
@@ -283,9 +283,9 @@ impl<O: FileOpener> Resolver<O> {
283283
accept_encoding: AcceptEncoding,
284284
) -> IoResult<ResolveResult<O::File>> {
285285
// Determine MIME-type. This needs to happen before we resolve a pre-encoded file.
286-
let mime = MimeGuess::from_path(&path)
286+
let mimetype = MimeGuess::from_path(&path)
287287
.first()
288-
.map(|mime| mime.to_string());
288+
.map(|mimetype| set_charset(mimetype).to_string());
289289

290290
// Resolve pre-encoded files.
291291
if accept_encoding.br {
@@ -295,7 +295,7 @@ impl<O: FileOpener> Resolver<O> {
295295
return Ok(ResolveResult::Found(ResolvedFile::new(
296296
file,
297297
br_path.into(),
298-
mime,
298+
mimetype,
299299
Some(Encoding::Br),
300300
)));
301301
}
@@ -307,15 +307,15 @@ impl<O: FileOpener> Resolver<O> {
307307
return Ok(ResolveResult::Found(ResolvedFile::new(
308308
file,
309309
gzip_path.into(),
310-
mime,
310+
mimetype,
311311
Some(Encoding::Gzip),
312312
)));
313313
}
314314
}
315315

316316
// No pre-encoded file found, serve the original.
317317
Ok(ResolveResult::Found(ResolvedFile::new(
318-
file, path, mime, None,
318+
file, path, mimetype, None,
319319
)))
320320
}
321321
}
@@ -401,3 +401,13 @@ impl BitAnd for AcceptEncoding {
401401
}
402402
}
403403
}
404+
405+
fn set_charset(mimetype: Mime) -> Mime {
406+
if mimetype == mime::APPLICATION_JAVASCRIPT {
407+
return mime::APPLICATION_JAVASCRIPT_UTF_8;
408+
}
409+
if mimetype == mime::TEXT_JAVASCRIPT {
410+
return "text/javascript; charset=utf-8".parse().unwrap();
411+
}
412+
mimetype
413+
}

tests/static.rs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -226,6 +226,19 @@ async fn changes_content_type_on_extension() {
226226
);
227227
}
228228

229+
#[tokio::test]
230+
async fn changes_content_type_on_extension_js() {
231+
let harness = Harness::new(vec![("file1.js", "this is file1")]);
232+
233+
let res = harness.get("/file1.js").await.unwrap();
234+
assert_eq!(
235+
res.headers().get(header::CONTENT_TYPE),
236+
Some(&header::HeaderValue::from_static(
237+
"text/javascript; charset=utf-8"
238+
))
239+
);
240+
}
241+
229242
#[tokio::test]
230243
async fn serves_file_with_old_if_modified_since() {
231244
let harness = Harness::new(vec![("file1.html", "this is file1")]);

0 commit comments

Comments
 (0)