http icon indicating copy to clipboard operation
http copied to clipboard

serde support for http::Uri

Open jplatte opened this issue 5 years ago • 5 comments
trafficstars

It would be nice if http::Uri implemented Deserialize and Serialize under a serde feature flag. Would a PR be welcome for this?

jplatte avatar Aug 11 '20 00:08 jplatte

Ping @seanmonstar

jplatte avatar Nov 19 '20 00:11 jplatte

Just in case someone ends up here and is looking for a simple workaround:

#[derive(Debug, Serialize, Deserialize)]
pub struct Uri {
    #[serde(with = "uri_serde")]
    pub uri: http::Uri,
}

mod uri_serde {
    use http::uri::InvalidUri;
    use serde::{de::Error as _, Deserialize, Deserializer, Serializer};

    pub fn deserialize<'de, D>(deserializer: D) -> Result<http::Uri, D::Error>
    where
        D: Deserializer<'de>,
    {
        let string = String::deserialize(deserializer)?;
        let uri = string.parse().map_err(|err: InvalidUri| D::Error::custom(err.to_string()))?;

        Ok(uri)
    }

    pub fn serialize<S>(uri: &http::Uri, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&uri.to_string())
    }
}

stoically avatar Aug 22 '21 09:08 stoically

You can use http_serde::uri.

tesaguri avatar Aug 22 '21 09:08 tesaguri

What if we want Serialize and Deserialize for HashMap<u64, Uri>? I think the http-serde doesn't work in this case but we need a wrapper around Uri. This way, the application code will have a lot of wrap and unwrap, which is a bit too noisy.

SInce url crates seems has a feature gate to enable serde for the type, what is the particular reason for this crate not to provide the same feature?

akiradeveloper avatar Mar 01 '22 16:03 akiradeveloper

I wrote a crate that provides Serialize and Deserialize for Uri as well as the other types from this crate. It also allows wrapping in Option, HashMap, and other std::collection types. https://crates.io/crates/http-serde-ext

andrewtoth avatar Oct 21 '23 23:10 andrewtoth