diff --git a/templates/http-rust/content/Cargo.toml.tmpl b/templates/http-rust/content/Cargo.toml.tmpl index bf6db35e6e..543a32cfa6 100644 --- a/templates/http-rust/content/Cargo.toml.tmpl +++ b/templates/http-rust/content/Cargo.toml.tmpl @@ -11,6 +11,15 @@ crate-type = ["cdylib"] [dependencies] anyhow = "1" +{%- case http-router -%} +{%- when "spin" %} +spin-sdk = { version = "6.0.0", features = ["router"] } +{%- when "axum" %} +axum = { version = "0.8.6", default-features = false, features = ["json", "macros"] } spin-sdk = "6.0.0" +tower-service = "0.3.3" +{%- else %} +spin-sdk = "6.0.0" +{%- endcase %} [workspace] diff --git a/templates/http-rust/content/src/lib.rs b/templates/http-rust/content/src/lib.rs index 0dc894976a..97df580aa3 100644 --- a/templates/http-rust/content/src/lib.rs +++ b/templates/http-rust/content/src/lib.rs @@ -1,3 +1,60 @@ +{%- case http-router -%} +{%- when "spin" -%} +// For the built-in router documentation refer to +// https://spinframework.dev/rust-components#the-spin-http-router +use spin_sdk::http::router::{Params, Router}; +use spin_sdk::http::{IntoResponse, Request, StatusCode}; +use spin_sdk::http_service; + +/// A simple Spin HTTP component using the built-in router. +#[http_service] +async fn handle_{{project-name | snake_case}}(req: Request) -> impl IntoResponse { + let mut router = Router::new(); + router.get("/", index); + router.get("/hello/:name", hello); + router.any("/*", not_found); + router.handle(req).await +} + +async fn index(_req: Request, _params: Params) -> impl IntoResponse { + (StatusCode::OK, "Hello, Spin!") +} + +async fn hello(_req: Request, params: Params) -> impl IntoResponse { + let name = params.get("name").unwrap_or("world").to_owned(); + (StatusCode::OK, format!("Hello, {name}!")) +} + +async fn not_found(_req: Request, _params: Params) -> impl IntoResponse { + (StatusCode::NOT_FOUND, "Not Found") +} +{%- when "axum" -%} +// For Axum documentation refer to https://docs.rs/axum/latest/axum/ +use axum::extract::Path; +use axum::routing::get; +use axum::Router; +use spin_sdk::http::{IntoResponse, Request}; +use spin_sdk::http_service; +use tower_service::Service; + +/// A simple Spin HTTP component using the Axum router. +#[http_service] +async fn handle_{{project-name | snake_case}}(req: Request) -> impl IntoResponse { + Router::new() + .route("/", get(index)) + .route("/hello/{name}", get(hello)) + .call(req) + .await +} + +async fn index() -> &'static str { + "Hello, Spin!" +} + +async fn hello(Path(name): Path) -> String { + format!("Hello, {name}!") +} +{%- else -%} use spin_sdk::http::{IntoResponse, Request, Response}; use spin_sdk::http_service; @@ -10,3 +67,4 @@ async fn handle_{{project-name | snake_case}}(req: Request) -> anyhow::Result