Change the return type of the method content_type from &str to Option<&str>

This commit is contained in:
Vinicius Buzzacaro 2025-11-10 21:40:11 -03:00
parent 219b988300
commit 539e86a544
1 changed files with 8 additions and 10 deletions

View File

@ -46,13 +46,11 @@ pub trait HttpMessage: Sized {
/// Read the request content type. If request did not contain a *Content-Type* header, an empty /// Read the request content type. If request did not contain a *Content-Type* header, an empty
/// string is returned. /// string is returned.
fn content_type(&self) -> &str { fn content_type(&self) -> Option<&str> {
if let Some(content_type) = self.headers().get(header::CONTENT_TYPE) { self.headers()
if let Ok(content_type) = content_type.to_str() { .get(header::CONTENT_TYPE)
return content_type.split(';').next().unwrap().trim(); .and_then(|ct| ct.to_str().ok())
} .map(|ct| ct.split(';').next().unwrap().trim())
}
""
} }
/// Get content type encoding. /// Get content type encoding.
@ -142,13 +140,13 @@ mod tests {
let req = TestRequest::default() let req = TestRequest::default()
.insert_header(("content-type", "text/plain")) .insert_header(("content-type", "text/plain"))
.finish(); .finish();
assert_eq!(req.content_type(), "text/plain"); assert_eq!(req.content_type(), Some("text/plain"));
let req = TestRequest::default() let req = TestRequest::default()
.insert_header(("content-type", "application/json; charset=utf-8")) .insert_header(("content-type", "application/json; charset=utf-8"))
.finish(); .finish();
assert_eq!(req.content_type(), "application/json"); assert_eq!(req.content_type(), Some("application/json"));
let req = TestRequest::default().finish(); let req = TestRequest::default().finish();
assert_eq!(req.content_type(), ""); assert_eq!(req.content_type(), None);
} }
#[test] #[test]