From d6b206f4944dd1844d0d19ae32142c95c0640317 Mon Sep 17 00:00:00 2001 From: someone Date: Thu, 18 Apr 2024 10:21:03 +0200 Subject: [PATCH] Implemented request parsing to struct example --- Cargo.lock | 2 ++ crates/server/Cargo.toml | 4 +++- crates/server/src/main.rs | 30 ++++++++++++++++++++++++------ 3 files changed, 29 insertions(+), 7 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 6931b9f..583f214 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -807,6 +807,8 @@ dependencies = [ "axum", "env_logger", "log", + "serde", + "serde_json", "tokio", "utoipa", ] diff --git a/crates/server/Cargo.toml b/crates/server/Cargo.toml index 6ca7040..265dfe0 100644 --- a/crates/server/Cargo.toml +++ b/crates/server/Cargo.toml @@ -14,4 +14,6 @@ log = { workspace = true } env_logger = { workspace = true } tokio = { workspace = true, features=["full"] } axum = { workspace = true } -utoipa = { version = "4", features = ["axum_extras"] } \ No newline at end of file +utoipa = { version = "4", features = ["axum_extras"] } +serde = "1.0.197" +serde_json = "1.0.1" \ No newline at end of file diff --git a/crates/server/src/main.rs b/crates/server/src/main.rs index 7cd9b58..9ada5e5 100644 --- a/crates/server/src/main.rs +++ b/crates/server/src/main.rs @@ -1,6 +1,8 @@ use axum::{extract::Request, routing::{get, post}, Router}; use log; use std::env; +use serde::Deserialize; +use serde_json; #[tokio::main] async fn main() { @@ -12,6 +14,7 @@ async fn main() { .route("/", get(root)) .route("/v1/secret/data/foo", post(foo)) .route_service("/v1/secret/data/bar", post(bar)) + .route("/v1/kw_mount_path/data/foo", post(baz)) .fallback(fallback); @@ -20,21 +23,36 @@ async fn main() { axum::serve(listener, app).await.unwrap(); } +#[derive(Deserialize,Debug)] +struct CreateSecret { + password1: String, + password2: String, +} + +/// Routing handler for path "/v1/kw_mount_path/data/foo" +/// expects payload as JSON, prints payload into struct +async fn baz(body: String) -> String{ + let mut body_json = serde_json::from_str::(body.as_str()).unwrap(); + let secret: CreateSecret = CreateSecret{password1: body_json["data"]["password1"].take().to_string(), password2: body_json["data"]["password2"].take().to_string()}; + log::debug!("Pass1: {}, Pass2: {}", secret.password1, secret.password2); + String::from("RoutingTest baz successful") +} + /// Test function foo for routing -async fn foo(req: Request) -> String { - log::debug!("`{:?}`", req); - String::from("RoutingTest foo successful") - +/// Returns body of request +async fn foo(body: String) -> String { + log::debug!("{:?}", body.as_str()); + String::from("RoutingTest foo successful") } /// Test function bar for routing async fn bar(req: Request)-> String { - log::debug!("`{:?}`", req); + log::debug!("{:?}", req); String::from("RoutingTest bar successful") } async fn fallback(req: Request)-> String { - log::debug!("`{:?}`", req); + log::debug!("{:?}", req); String::from("Fallback triggered") }