http-rs / http-types

Common types for HTTP operations
https://docs.rs/http-types
Apache License 2.0
200 stars 83 forks source link

Add `Mime::into_extension` #271

Open yoshuawuyts opened 3 years ago

yoshuawuyts commented 3 years ago

Tracking issue: #274

Add a method to try and convert an IANA media type into an extension. This is the inverse of Mime::from_extension which attempts to guess a mime type from an extension.

pepoviola commented 3 years ago

Hi @yoshuawuyts, I can take this one if no one is currently working on this. Thanks!

yoshuawuyts commented 3 years ago

@pepoviola that'd be great, thank you!

pepoviola commented 3 years ago

Hi @yoshuawuyts, thanks! quick question related to this issue. Is expected to return something like Option<impl AsRef<str>> ?

I was working in something like this.

+    /// Guess the mime type from a file extension
+    pub fn into_extension(self) -> Option<impl AsRef<str>> {
+        match self.subtype() {
+            "html" => Some("html"),
+            "javascript" => Some("js"),
+            "json" => Some("json"),
+            "css" => Some("css"),
+            "svg" => Some("svg"),
+            "xml" => Some("xml"),
+            _ => None,
+        }
+    }

Thanks for the guide and help! 🙌

brightly-salty commented 3 years ago

@pepoviola Based on my extremely limited knowledge, I would guess that it needs to return Option<&str>. You might need to do some lifetime magic. The reason the type of Mime::from_extension is AsRef<str> is so we can also convert str-like types to a Mime, but we don't need to replicate that in Mime::into_extension, as we can just return a &str.

Fishrock123 commented 3 years ago

That should return Option<&'static str>.

pepoviola commented 3 years ago

Thanks @Fishrock123, I will change to return Option<&'static str> .