http_protocol: implement axum IntoResponse, use in http_private

This commit is contained in:
Joakim Frostegård 2022-04-03 20:20:51 +02:00
parent 5e79df8e7e
commit 98e7e5cc13
6 changed files with 70 additions and 41 deletions

View file

@ -22,8 +22,12 @@ name = "bench_announce_response_to_bytes"
path = "benches/bench_announce_response_to_bytes.rs"
harness = false
[features]
with-axum = ["axum"]
[dependencies]
anyhow = "1"
axum = { version = "0.5", optional = true, default-features = false }
hex = { version = "0.4", default-features = false }
httparse = "1"
itoa = "1"

View file

@ -112,6 +112,21 @@ impl AnnounceResponse {
}
}
#[cfg(feature = "with-axum")]
impl axum::response::IntoResponse for AnnounceResponse {
fn into_response(self) -> axum::response::Response {
let mut response_bytes = Vec::with_capacity(128);
self.write(&mut response_bytes).unwrap();
(
[("Content-type", "text/plain; charset=utf-8")],
response_bytes,
)
.into_response()
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScrapeResponse {
/// BTreeMap instead of HashMap since keys need to be serialized in order
@ -142,6 +157,21 @@ impl ScrapeResponse {
}
}
#[cfg(feature = "with-axum")]
impl axum::response::IntoResponse for ScrapeResponse {
fn into_response(self) -> axum::response::Response {
let mut response_bytes = Vec::with_capacity(128);
self.write(&mut response_bytes).unwrap();
(
[("Content-type", "text/plain; charset=utf-8")],
response_bytes,
)
.into_response()
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FailureResponse {
#[serde(rename = "failure reason")]
@ -170,6 +200,21 @@ impl FailureResponse {
}
}
#[cfg(feature = "with-axum")]
impl axum::response::IntoResponse for FailureResponse {
fn into_response(self) -> axum::response::Response {
let mut response_bytes = Vec::with_capacity(64);
self.write(&mut response_bytes).unwrap();
(
[("Content-type", "text/plain; charset=utf-8")],
response_bytes,
)
.into_response()
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum Response {
@ -191,6 +236,17 @@ impl Response {
}
}
#[cfg(feature = "with-axum")]
impl axum::response::IntoResponse for Response {
fn into_response(self) -> axum::response::Response {
match self {
Self::Announce(r) => r.into_response(),
Self::Scrape(r) => r.into_response(),
Self::Failure(r) => r.into_response(),
}
}
}
#[cfg(test)]
impl quickcheck::Arbitrary for ResponsePeer<Ipv4Addr> {
fn arbitrary(g: &mut quickcheck::Gen) -> Self {