Skip to content

Commit

Permalink
fix(*): support mime type structured syntax suffix
Browse files Browse the repository at this point in the history
  • Loading branch information
flrgh committed Jun 5, 2024
1 parent 0675d80 commit 894b27f
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 2 deletions.
7 changes: 7 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,4 @@ proxy-wasm = "0.2"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
log = "0.4"
mime = "0.3.17"
35 changes: 33 additions & 2 deletions src/filter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,17 @@ proxy_wasm::main! {{

const CONTENT_LENGTH: &str = "content-length";
const CONTENT_TYPE: &str = "content-type";
const JSON_CONTENT_TYPE: &str = "application/json";

fn is_json_mime_type<T: AsRef<str>>(ct: T) -> bool {
let Ok(mt) = ct.as_ref().parse::<mime::Mime>() else {
return false;
};

matches!(
(mt.type_(), mt.subtype(), mt.suffix()),
(mime::APPLICATION, mime::JSON, _) | (mime::APPLICATION, _, Some(mime::JSON))
)
}

struct ResponseTransformerRoot {
config: Option<Rc<Config>>,
Expand Down Expand Up @@ -132,7 +142,7 @@ impl HttpContext for ResponseTransformerHttp {
impl ResponseTransformerHttp {
fn is_json_response(&self) -> bool {
self.get_http_response_header(CONTENT_TYPE)
.map_or(false, |ct| ct.eq_ignore_ascii_case(JSON_CONTENT_TYPE))
.map_or(false, is_json_mime_type)
}

fn transform_headers(&self, tx: &Headers) {
Expand Down Expand Up @@ -267,3 +277,24 @@ impl ResponseTransformerHttp {
self.set_http_response_body(0, body.len(), body.as_slice());
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_json_mime_type_detection() {
assert!(is_json_mime_type("application/json"));
assert!(is_json_mime_type("APPLICATION/json"));
assert!(is_json_mime_type("APPLICATION/JSON"));
assert!(is_json_mime_type("application/JSON"));
assert!(is_json_mime_type("application/json; charset=utf-8"));
assert!(is_json_mime_type("application/problem+json"));
assert!(is_json_mime_type("application/problem+JSON"));
assert!(is_json_mime_type("application/problem+json; charset=utf-8"));

assert!(!is_json_mime_type("text/plain"));
assert!(!is_json_mime_type("application/not-json"));
assert!(!is_json_mime_type("nope/json"));
}
}

0 comments on commit 894b27f

Please sign in to comment.