tide icon indicating copy to clipboard operation
tide copied to clipboard

tide::Response::set_content_type usage

Open zakarumych opened this issue 5 years ago • 8 comments

This function takes impl Into<Mime> as an input which is not so great from usability stand-point. Because Mime doesn't implement From for anything but itself.

On the other hand Mime implements FromStr which allows using it like this. "text/html".parse(). But it context of set_content_type call rustc cannot infer what type to parse to. It could if set_content_type would accept Mime type directly.

zakarumych avatar Jun 09 '20 10:06 zakarumych

https://github.com/http-rs/http-types/pull/179 should fix this for you when http-types is updated. This looks like it was an oversight from there.

Thought I do think the train of thought is that folks should try to use mime::TYPE instead (or Body's inbuilt from-file sniffing), to get the most "correct" type when usable.

Fishrock123 avatar Jun 09 '20 17:06 Fishrock123

Thought I do think the train of thought is that folks should try to use mime::TYPE instead (or Body's inbuilt from-file sniffing), to get the most "correct" type when usable.

Oh, I didn't even see those. Why not make them associated constants for Mime type itself? It would be much more discoverable.

zakarumych avatar Jun 10 '20 05:06 zakarumych

They already are...

That is quite certainly the recommended usage. If that doesn't support your use-case, perhaps try:

res.set_content_type(Mime::from_str("mime/type")?);

Fishrock123 avatar Jun 10 '20 17:06 Fishrock123

I see module level constants, not associated to a type. Mime::from_str requires FromStr to be in scope. Typically you don't import that trait, but use str::parse.

zakarumych avatar Jun 10 '20 18:06 zakarumych

Ah, true. Having the constants be on the struct feels a little weird but at very least I think the docs from Mime should recommend using them.

Fishrock123 avatar Jun 10 '20 21:06 Fishrock123

In my experience this is pretty common to define widely used values of the type as associated constants to that type. And benefits discoverability of those constants greatly.

IMHO, an expression TypeName::CONSTANT_NAME that produces TypeName value feels similar to a TypeName::constructor_function_name()

zakarumych avatar Jun 11 '20 07:06 zakarumych

Should be fixed whenever we pull in an http-types 2.4.0...

Fishrock123 avatar Jul 11 '20 22:07 Fishrock123

Wouldn't AsRef<Mime> be a lot nicer?

Doing res.set_content_type("text/html; charset=utf8"); may seem nice, but is error-prone and inefficient (having to parse the string and potentially panic only to format it again).

Doing res.set_content_type(MYTYPE) with a static ref, without having to clone it, would be nicer.

kaj avatar Aug 06 '20 20:08 kaj