Skip to content

Commit b75616d

Browse files
authored
fix(*): support mime type structured syntax suffix (#4)
1 parent 0675d80 commit b75616d

File tree

3 files changed

+41
-2
lines changed

3 files changed

+41
-2
lines changed

Cargo.lock

Lines changed: 7 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,3 +14,4 @@ proxy-wasm = "0.2"
1414
serde = { version = "1.0", features = ["derive"] }
1515
serde_json = "1.0"
1616
log = "0.4"
17+
mime = "0.3.17"

src/filter.rs

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,17 @@ proxy_wasm::main! {{
1919

2020
const CONTENT_LENGTH: &str = "content-length";
2121
const CONTENT_TYPE: &str = "content-type";
22-
const JSON_CONTENT_TYPE: &str = "application/json";
22+
23+
fn is_json_mime_type<T: AsRef<str>>(ct: T) -> bool {
24+
let Ok(mt) = ct.as_ref().parse::<mime::Mime>() else {
25+
return false;
26+
};
27+
28+
matches!(
29+
(mt.type_(), mt.subtype(), mt.suffix()),
30+
(mime::APPLICATION, mime::JSON, _) | (mime::APPLICATION, _, Some(mime::JSON))
31+
)
32+
}
2333

2434
struct ResponseTransformerRoot {
2535
config: Option<Rc<Config>>,
@@ -132,7 +142,7 @@ impl HttpContext for ResponseTransformerHttp {
132142
impl ResponseTransformerHttp {
133143
fn is_json_response(&self) -> bool {
134144
self.get_http_response_header(CONTENT_TYPE)
135-
.map_or(false, |ct| ct.eq_ignore_ascii_case(JSON_CONTENT_TYPE))
145+
.map_or(false, is_json_mime_type)
136146
}
137147

138148
fn transform_headers(&self, tx: &Headers) {
@@ -267,3 +277,24 @@ impl ResponseTransformerHttp {
267277
self.set_http_response_body(0, body.len(), body.as_slice());
268278
}
269279
}
280+
281+
#[cfg(test)]
282+
mod tests {
283+
use super::*;
284+
285+
#[test]
286+
fn test_json_mime_type_detection() {
287+
assert!(is_json_mime_type("application/json"));
288+
assert!(is_json_mime_type("APPLICATION/json"));
289+
assert!(is_json_mime_type("APPLICATION/JSON"));
290+
assert!(is_json_mime_type("application/JSON"));
291+
assert!(is_json_mime_type("application/json; charset=utf-8"));
292+
assert!(is_json_mime_type("application/problem+json"));
293+
assert!(is_json_mime_type("application/problem+JSON"));
294+
assert!(is_json_mime_type("application/problem+json; charset=utf-8"));
295+
296+
assert!(!is_json_mime_type("text/plain"));
297+
assert!(!is_json_mime_type("application/not-json"));
298+
assert!(!is_json_mime_type("nope/json"));
299+
}
300+
}

0 commit comments

Comments
 (0)