hyperium / http

Rust HTTP types
Apache License 2.0
1.16k stars 291 forks source link

serde support for http::Uri #434

Open jplatte opened 4 years ago

jplatte commented 4 years ago

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

jplatte commented 3 years ago

Ping @seanmonstar

stoically commented 3 years ago

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())
    }
}
tesaguri commented 3 years ago

You can use http_serde::uri.

akiradeveloper commented 2 years ago

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?

andrewtoth commented 1 year ago

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