activitypub-federation-rust/src/axum/json.rs

40 lines
1.5 KiB
Rust
Raw Normal View History

2023-03-06 01:17:34 +00:00
//! Wrapper struct to respond with `application/activity+json` in axum handlers
//!
//! ```
//! # use anyhow::Error;
//! # use axum::extract::Path;
2023-03-16 20:41:29 +00:00
//! # use activitypub_federation::axum::json::FederationJson;
2023-03-06 01:17:34 +00:00
//! # use activitypub_federation::protocol::context::WithContext;
//! # use activitypub_federation::config::Data;
2023-03-16 20:41:29 +00:00
//! # use activitypub_federation::traits::Object;
2023-03-06 01:17:34 +00:00
//! # use activitypub_federation::traits::tests::{DbConnection, DbUser, Person};
2023-03-16 20:41:29 +00:00
//! async fn http_get_user(Path(name): Path<String>, data: Data<DbConnection>) -> Result<FederationJson<WithContext<Person>>, Error> {
//! let user: DbUser = data.read_local_user(&name).await?;
2023-03-16 20:41:29 +00:00
//! let person = user.into_json(&data).await?;
2023-03-06 01:17:34 +00:00
//!
2023-03-16 20:41:29 +00:00
//! Ok(FederationJson(WithContext::new_default(person)))
2023-03-06 01:17:34 +00:00
//! }
//! ```
2023-03-16 20:41:29 +00:00
use crate::FEDERATION_CONTENT_TYPE;
use axum::response::IntoResponse;
use http::header;
use serde::Serialize;
2023-03-02 14:18:06 +00:00
/// Wrapper struct to respond with `application/activity+json` in axum handlers
#[derive(Debug, Clone, Copy, Default)]
2023-03-16 20:41:29 +00:00
pub struct FederationJson<Json: Serialize>(pub Json);
2023-03-16 20:41:29 +00:00
impl<Json: Serialize> IntoResponse for FederationJson<Json> {
fn into_response(self) -> axum::response::Response {
let mut response = axum::response::Json(self.0).into_response();
response.headers_mut().insert(
header::CONTENT_TYPE,
2023-03-16 20:41:29 +00:00
FEDERATION_CONTENT_TYPE
.parse()
.expect("Parsing 'application/activity+json' should never fail"),
);
response
}
}