Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 9 additions & 4 deletions examples/Rust/basic-rust-application-extended/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[package]
name = "myapp"
version = "0.1.0"
edition = "2021"
edition = "2024"

[lib]
crate-type = ["cdylib"]
Expand All @@ -11,11 +11,16 @@ package = "myorg:myapp"
proxy = false

[dependencies]
waki = { version = "0.5.0", features = ["json"] }
wstd = { version = "0.6.3", features = ["json"] }
wstd-axum = { version = "0.6.3" }
axum = { version = "0.8.8", default-features = false, features = [
"query",
"json",
"macros",
] }
serde = { version = "1.0.216", features = ["derive"] }
serde_json = "1.0.133"

# reduce wasm binary size
[profile.release]
lto = true
strip = "symbols"
strip = "symbols"
40 changes: 16 additions & 24 deletions examples/Rust/basic-rust-application-extended/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
use axum::{
Json,
routing::{Router, get},
};
use serde::{Deserialize, Serialize};
use waki::{handler, ErrorCode, Request, Response};

#[derive(Deserialize)]
struct MyRequestBody {
Expand All @@ -13,29 +16,18 @@ struct MyResponseBody {
msg: Option<String>,
}

#[handler]
fn hello(req: Request) -> Result<Response, ErrorCode> {
#[wstd_axum::http_server]
fn main() -> Router {
Router::new().route("/mypath", get(handler))
}

async fn handler(Json(body): Json<MyRequestBody>) -> Json<MyResponseBody> {
let message = std::env::var("HELLO_MESSAGE").expect("HELLO_MESSAGE is not set");
let body = match req.json::<MyRequestBody>() {
Ok(b) => b,
Err(_) => {
return Response::builder()
.status_code(400)
.json(&MyResponseBody {
error: Some("Missing request body".to_string()),
name: None,
msg: None,
})
.build();
}
};

Response::builder()
.status_code(200)
.json(&MyResponseBody {
error: None,
name: Some(body.name.clone()),
msg: Some(format!("{} {}", message, body.name)),
})
.build()
MyResponseBody {
error: None,
msg: Some(format!("{message} {}", body.name)),
name: Some(body.name),
}
.into()
}
12 changes: 9 additions & 3 deletions examples/Rust/basic-rust-application/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[package]
name = "myapp"
version = "0.1.0"
edition = "2021"
edition = "2024"

[lib]
crate-type = ["cdylib"]
Expand All @@ -11,9 +11,15 @@ package = "myorg:myapp"
proxy = false

[dependencies]
waki = { version = "0.5.0", features = ["json"] }
wstd = { version = "0.6.3", features = ["json"] }
wstd-axum = { version = "0.6.3" }
axum = { version = "0.8.8", default-features = false, features = [
"query",
"json",
"macros",
] }

# reduce wasm binary size
[profile.release]
lto = true
strip = "symbols"
strip = "symbols"
21 changes: 13 additions & 8 deletions examples/Rust/basic-rust-application/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
use waki::{handler, ErrorCode, Request, Response};
use axum::{
http::StatusCode,
response::IntoResponse,
routing::{Router, get},
};

#[handler]
fn hello(req: Request) -> Result<Response, ErrorCode> {
Response::builder()
.status_code(200)
.body("Hello World")
.build()
}
#[wstd_axum::http_server]
fn main() -> Router {
Router::new().route("/myapp", get(handler))
}

async fn handler() -> impl IntoResponse {
(StatusCode::OK, "Hello, World!").into_response()
}
15 changes: 10 additions & 5 deletions examples/Rust/multi-path-application/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[package]
name = "multi-path-app"
version = "0.1.0"
edition = "2021"
edition = "2024"

[lib]
crate-type = ["cdylib"]
Expand All @@ -11,11 +11,16 @@ package = "myorg:multi-path-app"
proxy = false

[dependencies]
waki = { version = "0.5.0", features = ["json"] }
serde = { version = "1.0.216", features = ["derive"] }
serde_json = "1.0.133"
wstd = { version = "0.6.3", features = ["json"] }
wstd-axum = { version = "0.6.3" }
axum = { version = "0.8.8", default-features = false, features = [
"query",
"json",
"macros",
] }
serde = { version = "1.0.228", features = ["derive"] }

# reduce wasm binary size
[profile.release]
lto = true
strip = "symbols"
strip = "symbols"
121 changes: 57 additions & 64 deletions examples/Rust/multi-path-application/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,88 +1,81 @@
use axum::{
Json,
extract::Query,
http::{Response, StatusCode, header::CONTENT_TYPE},
response::IntoResponse,
routing::{Router, get, post},
};
use serde::{Deserialize, Serialize};
use std::{collections::HashMap, time::Duration};
use waki::{handler, header::ACCEPT, header::CONTENT_TYPE, ErrorCode, Method, Request, Response};
use wstd::http::Body;

pub const GET_QUERY_PATH: &str = "/multi-path-app/v1/get";
pub const POST_BODY_PATH: &str = "/multi-path-app/v1/post";
#[wstd_axum::http_server]
fn main() -> Router {
Router::new()
.route("/multi-path-app/v1/get", get(get_body_handler))
.route("/multi-path-app/v1/post", post(post_body_handler))
.fallback(async || (StatusCode::NOT_FOUND, "NOT FOUND!").into_response())
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SearchQuery {
search_text: String,
result_limit: i32,
}

#[handler]
fn hello(req: Request) -> Result<Response, ErrorCode> {
let path = &req.path().to_string();
let query = &req.query();
let method = &req.method();

//Here we have implemented a really simple router based on method and path in the request.
match (method, path.as_str()) {
(Method::Post, POST_BODY_PATH) => {
let body = match &req.body() {
Ok(body_value) => body_value.clone(),
Err(err) => {
return bad_request(format!("Invalid body request sent, {err:#?}").as_str())
}
};
post_body_handler(&body)
#[axum::debug_handler]
async fn get_body_handler(Query(params): Query<HashMap<String, String>>) -> Response<String> {
let _search: String = match params.get("search") {
Some(search) => search.to_string(),
None => {
return Response::builder()
.status(StatusCode::BAD_REQUEST)
.body("We are missing the required query param called Search".to_string())
.unwrap();
}
(Method::Get, GET_QUERY_PATH) => get_body_handler(query),
_ => not_found(),
}
}
};

pub fn not_found() -> Result<Response, ErrorCode> {
Response::builder()
.status_code(404)
.body("NOT FOUND!".to_string())
.build()
}
let mut client = wstd::http::Client::new();
client.set_connect_timeout(Duration::from_secs(1));

/// Bad request response
pub fn bad_request(msg: &str) -> Result<Response, ErrorCode> {
Response::builder()
.status_code(400)
.body(msg.to_string())
.build()
}
let request = wstd::http::Request::get("https://dummyjson.com/recipes/1")
.header("Content-Type", "application/json")
.header("Accept", "*")
.body(Body::empty())
.unwrap();

pub fn get_body_handler(query: &HashMap<String, String>) -> Result<Response, ErrorCode> {
let _search: String = match query.get("search") {
Some(search) => search.to_string(),
None => return bad_request("We are missing the required query param called Search"),
let result = match client.send(request).await {
Ok(result) => result,
Err(e) => {
return Response::builder()
.status(StatusCode::INTERNAL_SERVER_ERROR)
.body(format!("Failed to send request with error: {e}"))
.unwrap();
}
};

let client = waki::Client::new();
let result = client
.get("https://dummyjson.com/recipes/1")
.headers([("Content-Type", "application/json"), ("Accept", "*")])
.connect_timeout(Duration::from_secs(1))
.send()
.and_then(|res| res.body().map_err(|e| e.into()))
.and_then(|body| String::from_utf8(body).map_err(|e| e.into()));
let body = match result {
Ok(text_body) => text_body,
Err(err) => format!("We failed to retrieve the response: {err}"),
let body = match result.into_body().str_contents().await {
Ok(text_body) => text_body.to_string(),
Err(e) => {
return Response::builder()
.status(StatusCode::INTERNAL_SERVER_ERROR)
.body(format!("Failed to retrieve the response: {e}"))
.unwrap();
}
};

Response::builder()
.status_code(200)
.headers([(CONTENT_TYPE, "application/json")])
.status(StatusCode::OK)
.header(CONTENT_TYPE, "application/json")
.body(body)
.build()
.unwrap()
}

/// Post body response
pub fn post_body_handler(body: &Vec<u8>) -> Result<Response, ErrorCode> {
match serde_json::from_slice::<SearchQuery>(&body) {
Ok(value) => Response::builder()
.status_code(200)
.body(format!(
"We received the following search query: {value:#?}"
))
.build(),
Err(err) => bad_request(&format!("Failed deserialize the json body: {err}")),
}
async fn post_body_handler(Json(body): Json<SearchQuery>) -> impl IntoResponse {
(
StatusCode::OK,
format!("We received the following search query: {body:#?}"),
)
.into_response()
}
12 changes: 9 additions & 3 deletions templates/rust-http/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[package]
name = "{{name}}"
version = "0.1.0"
edition = "2021"
edition = "2024"

[lib]
crate-type = ["cdylib"]
Expand All @@ -11,9 +11,15 @@ package = "myorg:{{name}}"
proxy = false

[dependencies]
waki = { version = "0.5.0", features = ["json"] }
wstd = { version = "0.6.3", features = ["json"] }
wstd-axum = { version = "0.6.3" }
axum = { version = "0.8.8", default-features = false, features = [
"query",
"json",
"macros",
] }

# reduce wasm binary size
[profile.release]
lto = true
strip = "symbols"
strip = "symbols"
21 changes: 13 additions & 8 deletions templates/rust-http/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
use waki::{handler, ErrorCode, Request, Response};
use axum::{
http::StatusCode,
response::IntoResponse,
routing::{get, Router},
};

#[handler]
fn hello(req: Request) -> Result<Response, ErrorCode> {
Response::builder()
.status_code(200)
.body("Hello World")
.build()
}
#[wstd_axum::http_server]
fn main() -> Router {
Router::new().route("/hello", get(handler))
}

async fn handler() -> impl IntoResponse {
(StatusCode::Ok, "Hello, World!").into_response()
}