From 4ddcecb6501ce8704e16d6edb90fe7b46a5d8836 Mon Sep 17 00:00:00 2001 From: Avery Date: Tue, 29 Apr 2025 23:47:48 +0200 Subject: [PATCH] Implement `IntoResponse` for `UsersResponse` - Manually serialze the UsersResponse to json and set the correct content type --- Cargo.lock | 1 + Cargo.toml | 1 + src/main.rs | 8 ++++---- src/users.rs | 20 ++++++++++++++++---- 4 files changed, 22 insertions(+), 8 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 0242075..e273e19 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1116,6 +1116,7 @@ dependencies = [ "log", "rsa", "serde", + "serde_json", "sha2", "tokio", "tower-layer", diff --git a/Cargo.toml b/Cargo.toml index 59765ed..c0aa6b7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,6 +9,7 @@ env_logger = "0.11.8" log = "0.4.27" rsa = "0.9.8" serde = { version = "1.0.219", features = ["derive"] } +serde_json = "1.0.140" sha2 = "0.10.8" tokio = { version = "1.44.2", features = ["full"] } tower-layer = "0.3.3" diff --git a/src/main.rs b/src/main.rs index 1860bbe..d298a87 100644 --- a/src/main.rs +++ b/src/main.rs @@ -46,20 +46,20 @@ async fn fallback(uri: Uri) -> (StatusCode, String) { pub struct TraceLayer; impl Layer for TraceLayer { - type Service = LogService; + type Service = TraceService; fn layer(&self, service: S) -> Self::Service { - LogService { service } + TraceService { service } } } // This service implements the Log behavior #[derive(Clone)] -pub struct LogService { +pub struct TraceService { service: S, } -impl Service for LogService +impl Service for TraceService where S: Service, Request: fmt::Debug, diff --git a/src/users.rs b/src/users.rs index d47dcb0..b139190 100644 --- a/src/users.rs +++ b/src/users.rs @@ -1,4 +1,7 @@ -use axum::{Json, extract::Path}; +use axum::{ + extract::Path, + response::{IntoResponse, Response}, +}; use log::debug; use serde::Serialize; @@ -13,14 +16,23 @@ pub struct UsersResponse { id: String, } -pub async fn users_get(Path(user): Path) -> Json { +pub async fn users_get(Path(user): Path) -> UsersResponse { debug!("Got request for actor: {user}"); assert_eq!(user, USER); - Json(UsersResponse { + UsersResponse { context: "https://www.w3.org/ns/activitystreams".to_string(), r#type: "Person".to_string(), name: "Sally Smith".to_string(), id: "https://testhost.com/users/test".to_string(), - }) + } +} + +impl IntoResponse for UsersResponse { + fn into_response(self) -> Response { + Response::builder() + .header("content-type", "application/activity+json; charset=utf-8") + .body(serde_json::to_string(&self).unwrap().into()) + .unwrap() + } }