From 181259ecdd0b7c6c20d49a2bc108ceaab4ee8c37 Mon Sep 17 00:00:00 2001 From: jonaro00 <54029719+jonaro00@users.noreply.github.com> Date: Thu, 4 Jan 2024 16:20:22 +0100 Subject: [PATCH] update examples to axum 0.7 --- _snippets/check-examples.mdx | 1 + _snippets/other-frameworks.mdx | 1 + examples/actix-cookie-authentication.mdx | 4 +- examples/actix-postgres.mdx | 4 +- examples/actix-static-files.mdx | 4 +- examples/actix-websocket-actorless.mdx | 4 +- examples/actix.mdx | 4 +- examples/axum-jwt-authentication.mdx | 77 ++++++++++++---------- examples/axum-postgres.mdx | 83 +++++++++++------------- examples/axum-static-files.mdx | 17 +++-- examples/axum-websockets.mdx | 39 ++++------- examples/axum.mdx | 7 +- examples/poise.mdx | 4 +- examples/rocket-postgres.mdx | 4 +- examples/rocket-static-files.mdx | 4 +- examples/rocket.mdx | 4 +- examples/serenity.mdx | 4 +- 17 files changed, 130 insertions(+), 135 deletions(-) create mode 100644 _snippets/check-examples.mdx create mode 100644 _snippets/other-frameworks.mdx diff --git a/_snippets/check-examples.mdx b/_snippets/check-examples.mdx new file mode 100644 index 0000000..569795c --- /dev/null +++ b/_snippets/check-examples.mdx @@ -0,0 +1 @@ + Be sure to check out the [examples repo](https://github.com/shuttle-hq/shuttle-examples) for many more examples! diff --git a/_snippets/other-frameworks.mdx b/_snippets/other-frameworks.mdx new file mode 100644 index 0000000..e8a505f --- /dev/null +++ b/_snippets/other-frameworks.mdx @@ -0,0 +1 @@ + If you want to explore other frameworks, we have more examples with popular ones like Tower and Warp. You can find them [right here](/examples/other). diff --git a/examples/actix-cookie-authentication.mdx b/examples/actix-cookie-authentication.mdx index cb7cdfc..76c9458 100644 --- a/examples/actix-cookie-authentication.mdx +++ b/examples/actix-cookie-authentication.mdx @@ -158,6 +158,6 @@ Looking to extend this example? Here's a couple of ideas to get you started: --- - If you want to explore other frameworks, we have more examples with popular ones like Tower and Warp. You can find them [right here](../examples/other). + - Be sure to check out the [examples repo](https://github.com/shuttle-hq/shuttle-examples) for many more examples! + diff --git a/examples/actix-postgres.mdx b/examples/actix-postgres.mdx index 6bee7f6..300f2c5 100644 --- a/examples/actix-postgres.mdx +++ b/examples/actix-postgres.mdx @@ -146,6 +146,6 @@ Interested in extending this example? Here's as couple of ideas: - Add static files to show your records --- - If you want to explore other frameworks, we have more examples with popular ones like Tower and Warp. You can find them [right here](../examples/other). + - Be sure to check out the [examples repo](https://github.com/shuttle-hq/shuttle-examples) for many more examples! + diff --git a/examples/actix-static-files.mdx b/examples/actix-static-files.mdx index 68cb018..50725e1 100644 --- a/examples/actix-static-files.mdx +++ b/examples/actix-static-files.mdx @@ -78,6 +78,6 @@ You can extend this example by adding more routes that serve other files. --- - If you want to explore other frameworks, we have more examples with popular ones like Tower and Warp. You can find them [right here](../examples/other). + - Be sure to check out the [examples repo](https://github.com/shuttle-hq/shuttle-examples) for many more examples! + diff --git a/examples/actix-websocket-actorless.mdx b/examples/actix-websocket-actorless.mdx index 91d29b4..8b51b4d 100644 --- a/examples/actix-websocket-actorless.mdx +++ b/examples/actix-websocket-actorless.mdx @@ -424,6 +424,6 @@ Once you've cloned the example, launch it locally using `cargo shuttle run` and --- - If you want to explore other frameworks, we have more examples with popular ones like Tower and Warp. You can find them [right here](../examples/other). + - Be sure to check out the [examples repo](https://github.com/shuttle-hq/shuttle-examples) for many more examples! + diff --git a/examples/actix.mdx b/examples/actix.mdx index ab71717..f3e08bb 100644 --- a/examples/actix.mdx +++ b/examples/actix.mdx @@ -53,6 +53,6 @@ tokio = "1.26.0" --- - If you want to explore other frameworks, we have more examples with popular ones like Tower and Warp. You can find them [right here](../examples/other). + - Be sure to check out the [examples repo](https://github.com/shuttle-hq/shuttle-examples) for many more examples! + diff --git a/examples/axum-jwt-authentication.mdx b/examples/axum-jwt-authentication.mdx index 10806b3..ef7bcf1 100644 --- a/examples/axum-jwt-authentication.mdx +++ b/examples/axum-jwt-authentication.mdx @@ -17,50 +17,37 @@ Three Axum routes are registered in this file: - `/private`: a route that can only be accessed with a valid JWT. You can clone the example below by running the following (you'll need `cargo-shuttle` installed): -```bash + +```bash cargo shuttle init --from shuttle-hq/shuttle-examples \ - --subfolder axum/jwt-authentication + --subfolder axum/jwt-authentication ``` ## Code -```toml Cargo.toml -[package] -name = "authentication" -version = "0.1.0" -edition = "2021" - -[dependencies] -axum = { version = "0.6.18", features = ["headers"] } -jsonwebtoken = "8.3.0" -once_cell = "1.18.0" -serde = { version = "1.0.188", features = ["derive"] } -serde_json = "1.0.107" -shuttle-axum = "0.27.0" -shuttle-runtime = "0.27.0" -tokio = "1.28.2" -tracing-subscriber = "0.3.17" -``` -Your `main.rs` should look like this: - -```Rust main.rs + +```rust main.rs use axum::{ async_trait, extract::FromRequestParts, - headers::{authorization::Bearer, Authorization}, http::{request::Parts, StatusCode}, response::{IntoResponse, Response}, routing::{get, post}, - Json, RequestPartsExt, Router, TypedHeader, + Json, RequestPartsExt, Router, +}; +use axum_extra::{ + headers::{authorization::Bearer, Authorization}, + TypedHeader, }; use jsonwebtoken::{decode, encode, DecodingKey, EncodingKey, Header, Validation}; use once_cell::sync::Lazy; use serde::{Deserialize, Serialize}; use serde_json::json; use std::fmt::Display; +use std::time::SystemTime; static KEYS: Lazy = Lazy::new(|| { -// note that in production, you will probably want to use a random SHA-256 hash or similar + // note that in production, you will probably want to use a random SHA-256 hash or similar let secret = "JWT_SECRET".to_string(); Keys::new(secret.as_bytes()) }); @@ -98,13 +85,17 @@ async fn login(Json(payload): Json) -> Result, AuthE } // add 5 minutes to current unix epoch time as expiry date/time - let exp = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).as_secs() + 300; - + let exp = SystemTime::now() + .duration_since(SystemTime::UNIX_EPOCH) + .unwrap() + .as_secs() + + 300; + let claims = Claims { sub: "b@b.com".to_owned(), company: "ACME".to_owned(), - // Mandatory expiry time as UTC timestamp - exp: usize::try_from(exp).unwrap() + // Mandatory expiry time as UTC timestamp - takes unix epoch + exp: usize::try_from(exp).unwrap(), }; // Create the authorization token let token = encode(&Header::default(), &claims, &KEYS.encoding) @@ -170,7 +161,7 @@ impl IntoResponse for AuthError { } } -// encoding/decoding keys - set in the static `once_cell` above +// encoding/decoding keys - set in the static `once_cell` above struct Keys { encoding: EncodingKey, decoding: DecodingKey, @@ -207,7 +198,7 @@ struct AuthPayload { client_secret: String, } -// error types for auth errors +// error types for auth errors #[derive(Debug)] enum AuthError { WrongCredentials, @@ -217,6 +208,26 @@ enum AuthError { } ``` +```toml Cargo.toml +[package] +name = "authentication" +version = "0.1.0" +edition = "2021" + +[dependencies] +axum = "0.7.3" +axum-extra = { version = "0.9.1", features = ["typed-header"] } +jsonwebtoken = "8.3.0" +once_cell = "1.18.0" +serde = { version = "1.0.188", features = ["derive"] } +serde_json = "1.0.107" +shuttle-axum = "0.35.0" +shuttle-runtime = "0.35.0" +tokio = "1.28.2" +tracing-subscriber = "0.3.17" +``` + + ## Usage Once you've cloned this example, launch it locally by using `cargo shuttle run`. Once you've verified that it's up, you'll now be able to go to `http://localhost:8000` and start trying the example out! @@ -256,6 +267,6 @@ Looking to extend this example? Here's a couple of ideas to get you started: --- - If you want to explore other frameworks, we have more examples with popular ones like Tower and Warp. You can find them [right here](../examples/other). + - Be sure to check out the [examples repo](https://github.com/shuttle-hq/shuttle-examples) for many more examples! + diff --git a/examples/axum-postgres.mdx b/examples/axum-postgres.mdx index 378e046..3566bc3 100644 --- a/examples/axum-postgres.mdx +++ b/examples/axum-postgres.mdx @@ -3,7 +3,7 @@ title: "Postgres Todo App" description: "This article walks you through how you can easily set up a simple to-do app using Axum and SQLx with PostgresQL." --- -## Description +## Description This example shows how to make a simple TODO app using Axum and a shared Shuttle Postgres DB. The following routes are provided: @@ -11,50 +11,53 @@ The following routes are provided: - POST `/todos` - Create a to-do item. Takes "note" as a JSON body parameter. You can clone the example below by running the following (you'll need `cargo-shuttle` installed): -```bash + +```bash cargo shuttle init --from shuttle-hq/shuttle-examples \ - --subfolder axum/postgres + --subfolder axum/postgres ``` ## Code ```rust src/main.rs -use axum::{Json, - extract::{Path, State}, - http::StatusCode, - response::IntoResponse, - Router, - routing::{post, get}}; +use axum::{ + extract::{Path, State}, + http::StatusCode, + response::IntoResponse, + routing::{get, post}, + Json, Router, +}; use serde::{Deserialize, Serialize}; use shuttle_runtime::CustomError; use sqlx::{FromRow, PgPool}; async fn retrieve( - Path(id): Path, - State(state): State - ) -> Result { + Path(id): Path, + State(state): State, +) -> Result { match sqlx::query_as::<_, Todo>("SELECT * FROM todos WHERE id = $1") .bind(id) .fetch_one(&state.pool) - .await { - Ok(todo) => Ok((StatusCode::OK, Json(todo))), - Err(e) => Err((StatusCode::BAD_REQUEST, e.to_string())) - } + .await + { + Ok(todo) => Ok((StatusCode::OK, Json(todo))), + Err(e) => Err((StatusCode::BAD_REQUEST, e.to_string())), + } } async fn add( State(state): State, Json(data): Json, ) -> Result { - match sqlx::query_as::<_, Todo>( - "INSERT INTO todos (note) VALUES ($1) RETURNING id, note" - ).bind(&data.note) + match sqlx::query_as::<_, Todo>("INSERT INTO todos (note) VALUES ($1) RETURNING id, note") + .bind(&data.note) .fetch_one(&state.pool) - .await { - Ok(todo) => Ok((StatusCode::CREATED, Json(todo))), - Err(e) => Err((StatusCode::BAD_REQUEST, e.to_string())) - } + .await + { + Ok(todo) => Ok((StatusCode::CREATED, Json(todo))), + Err(e) => Err((StatusCode::BAD_REQUEST, e.to_string())), + } } #[derive(Clone)] @@ -63,17 +66,16 @@ struct MyState { } #[shuttle_runtime::main] -async fn axum( - #[shuttle_shared_db::Postgres] pool: PgPool - ) -> shuttle_axum::ShuttleAxum { - sqlx::migrate!().run(&pool) +async fn axum(#[shuttle_shared_db::Postgres] pool: PgPool) -> shuttle_axum::ShuttleAxum { + sqlx::migrate!() + .run(&pool) .await .map_err(CustomError::new)?; let state = MyState { pool }; let router = Router::new() .route("/todos", post(add)) - .route("/todos/:id", get(retrieve)) + .route("/todos/:id", get(retrieve)) .with_state(state); Ok(router.into()) @@ -91,15 +93,6 @@ struct Todo { } ``` -```sql migrations/1_schema.sql -DROP TABLE IF EXISTS todos; - -CREATE TABLE todos ( - id serial PRIMARY KEY, - note TEXT NOT NULL -); -``` - ```toml Cargo.toml [package] name = "postgres" @@ -107,13 +100,13 @@ version = "0.1.0" edition = "2021" [dependencies] -axum = "0.6.18" -serde = { version = "1.0.148", features = ["derive"] } -shuttle-shared-db = { version = "0.27.0", features = ["postgres"] } -shuttle-axum = "0.27.0" -shuttle-runtime = "0.27.0" +axum = "0.7.3" +serde = { version = "1.0.188", features = ["derive"] } +shuttle-axum = "0.35.0" +shuttle-runtime = "0.35.0" +shuttle-shared-db = { version = "0.35.0", features = ["postgres"] } sqlx = { version = "0.7.1", features = ["runtime-tokio-native-tls", "postgres"] } -tokio = "1.26.0" +tokio = "1.28.2" ``` @@ -137,6 +130,6 @@ Interested in extending this example? Here's as couple of ideas: - Add static files to show your records --- - If you want to explore other frameworks, we have more examples with popular ones like Tower and Warp. You can find them [right here](../examples/other). + - Be sure to check out the [examples repo](https://github.com/shuttle-hq/shuttle-examples) for many more examples! + diff --git a/examples/axum-static-files.mdx b/examples/axum-static-files.mdx index 221aeb0..344bff0 100644 --- a/examples/axum-static-files.mdx +++ b/examples/axum-static-files.mdx @@ -10,17 +10,16 @@ This example has one route at `/` where the homepage is served and shows you how Note that static assets are declared in the `Shuttle.toml` file. You can clone the example below by running the following (you'll need `cargo-shuttle` installed): + ```bash cargo shuttle init --from shuttle-hq/shuttle-examples \ - --subfolder axum/static-files + --subfolder axum/static-files ``` ## Code ```rust src/main.rs -use std::path::PathBuf; - use axum::{routing::get, Router}; use tower_http::services::ServeDir; @@ -29,10 +28,10 @@ async fn hello_world() -> &'static str { } #[shuttle_runtime::main] -async fn axum() -> shuttle_axum::ShuttleAxum { +async fn main() -> shuttle_axum::ShuttleAxum { let router = Router::new() .route("/", get(hello_world)) - .nest_service("/assets", ServeDir::new(PathBuf::from("assets"))); + .nest_service("/assets", ServeDir::new("assets")); Ok(router.into()) } @@ -58,11 +57,11 @@ edition = "2021" publish = false [dependencies] -axum = "0.6.18" +axum = "0.7.3" shuttle-axum = "0.35.0" shuttle-runtime = "0.35.0" tokio = "1.28.2" -tower-http = { version = "0.4.0", features = ["fs"] } +tower-http = { version = "0.5.0", features = ["fs"] } ``` ```toml Shuttle.toml @@ -78,6 +77,6 @@ You can extend this example by adding more routes that serve other files. --- - If you want to explore other frameworks, we have more examples with popular ones like Tower and Warp. You can find them [right here](../examples/other). + - Be sure to check out the [examples repo](https://github.com/shuttle-hq/shuttle-examples) for many more examples! + diff --git a/examples/axum-websockets.mdx b/examples/axum-websockets.mdx index d5ac9ea..5175624 100644 --- a/examples/axum-websockets.mdx +++ b/examples/axum-websockets.mdx @@ -10,18 +10,19 @@ This example shows how to use a WebSocket to show the live status of the Shuttle There are a few routes available: - `/` - the homepage route where you can find the `index.html` page. - `/ws` - the route that handles websockets. - + You can clone the example below by running the following (you'll need `cargo-shuttle` installed): + ```bash cargo shuttle init --from shuttle-hq/shuttle-examples \ - --subfolder axum/websocket + --subfolder axum/websocket ``` ## Code ```rust src/main.rs -use std::{path::PathBuf, sync::Arc, time::Duration}; +use std::{sync::Arc, time::Duration}; use axum::{ extract::{ @@ -34,8 +35,6 @@ use axum::{ }; use chrono::{DateTime, Utc}; use futures::{SinkExt, StreamExt}; -use hyper::{Client, Uri}; -use hyper_tls::HttpsConnector; use serde::Serialize; use shuttle_axum::ShuttleAxum; use tokio::{ @@ -44,7 +43,6 @@ use tokio::{ }; use tower_http::services::ServeDir; - struct State { clients_count: usize, rx: watch::Receiver, @@ -63,10 +61,8 @@ struct Response { #[shuttle_runtime::main] async fn axum() -> ShuttleAxum { -// create a receiver/sender for a channel for us to send and receive messages over let (tx, rx) = watch::channel(Message::Text("{}".to_string())); -// generate state let state = Arc::new(Mutex::new(State { clients_count: 0, rx, @@ -76,16 +72,10 @@ async fn axum() -> ShuttleAxum { let state_send = state.clone(); tokio::spawn(async move { let duration = Duration::from_secs(PAUSE_SECS); - let https = HttpsConnector::new(); - let client = Client::builder().build::<_, hyper::Body>(https); - let uri: Uri = STATUS_URI.parse().unwrap(); - - // every 15 seconds, send a HTTP request to the URL we want to check - + loop { - // if OK, send a response to all connected clients - // if not, break loop - let is_up = client.get(uri.clone()).await.is_ok(); + let is_up = reqwest::get(STATUS_URI).await; + let is_up = is_up.is_ok(); let response = Response { clients_count: state_send.lock().await.clients_count, @@ -93,7 +83,7 @@ async fn axum() -> ShuttleAxum { is_up, }; let msg = serde_json::to_string(&response).unwrap(); - + if tx.send(Message::Text(msg)).is_err() { break; } @@ -104,7 +94,7 @@ async fn axum() -> ShuttleAxum { let router = Router::new() .route("/websocket", get(websocket_handler)) - .nest_service("/", ServeDir::new(PathBuf::from("static"))) + .nest_service("/", ServeDir::new("static")) .layer(Extension(state)); Ok(router.into()) @@ -270,17 +260,16 @@ version = "0.1.0" edition = "2021" [dependencies] -axum = { version = "0.6.18", features = ["ws"] } +axum = { version = "0.7.3", features = ["ws"] } chrono = { version = "0.4.26", features = ["serde"] } futures = "0.3.28" -hyper = { version = "0.14.26", features = ["client", "http2"] } -hyper-tls = "0.5.0" +reqwest = "0.11.23" serde = { version = "1.0.163", features = ["derive"] } serde_json = "1.0.96" shuttle-axum = "0.35.0" shuttle-runtime = "0.35.0" tokio = "1.28.2" -tower-http = { version = "0.4.0", features = ["fs"] } +tower-http = { version = "0.5.0", features = ["fs"] } ``` ```toml Shuttle.toml @@ -294,6 +283,6 @@ Once you've cloned the example, launch it locally using `cargo shuttle run` and --- - If you want to explore other frameworks, we have more examples with popular ones like Tower and Warp. You can find them [right here](../examples/other). + - Be sure to check out the [examples repo](https://github.com/shuttle-hq/shuttle-examples) for many more examples! + diff --git a/examples/axum.mdx b/examples/axum.mdx index 1d19c36..41054e7 100644 --- a/examples/axum.mdx +++ b/examples/axum.mdx @@ -13,6 +13,7 @@ This section revolves around simple Axum examples you can get quickly started wi If you are looking for step-by-step guides, check out our [How To](../tutorials) section. You can clone the example below by running the following (you'll need `cargo-shuttle` installed): + ```bash cargo shuttle init --template axum ``` @@ -41,7 +42,7 @@ version = "0.1.0" edition = "2021" [dependencies] -axum = "0.6.18" +axum = "0.7.3" shuttle-axum = "0.35.0" shuttle-runtime = "0.35.0" tokio = "1.28.2" @@ -50,6 +51,6 @@ tokio = "1.28.2" --- - If you want to explore other frameworks, we have more examples with popular ones like Tower and Warp. You can find them [right here](../examples/other). + - Be sure to check out the [examples repo](https://github.com/shuttle-hq/shuttle-examples) for many more examples! + diff --git a/examples/poise.mdx b/examples/poise.mdx index c5462d5..0eced68 100644 --- a/examples/poise.mdx +++ b/examples/poise.mdx @@ -80,6 +80,6 @@ tokio = "1.28.2" --- - If you want to explore other frameworks, we have more examples with popular ones like Tower and Warp. You can find them [right here](../examples/other). + - Be sure to check out the [examples repo](https://github.com/shuttle-hq/shuttle-examples) for many more examples! + diff --git a/examples/rocket-postgres.mdx b/examples/rocket-postgres.mdx index e2bacbf..ffbef06 100644 --- a/examples/rocket-postgres.mdx +++ b/examples/rocket-postgres.mdx @@ -132,6 +132,6 @@ Interested in extending this example? Here's as couple of ideas: - Add static files to show your records --- - If you want to explore other frameworks, we have more examples with popular ones like Tower and Warp. You can find them [right here](../examples/other). + - Be sure to check out the [examples repo](https://github.com/shuttle-hq/shuttle-examples) for many more examples! + diff --git a/examples/rocket-static-files.mdx b/examples/rocket-static-files.mdx index 00b9128..3da812f 100644 --- a/examples/rocket-static-files.mdx +++ b/examples/rocket-static-files.mdx @@ -94,6 +94,6 @@ You can extend this example by adding more routes that serve other files. --- - If you want to explore other frameworks, we have more examples with popular ones like Tower and Warp. You can find them [right here](../examples/other). + - Be sure to check out the [examples repo](https://github.com/shuttle-hq/shuttle-examples) for many more examples! + diff --git a/examples/rocket.mdx b/examples/rocket.mdx index 7691012..b0967f1 100644 --- a/examples/rocket.mdx +++ b/examples/rocket.mdx @@ -51,6 +51,6 @@ tokio = "1.26.0" --- - If you want to explore other frameworks, we have more examples with popular ones like Tower and Warp. You can find them [right here](../examples/other). + - Be sure to check out the [examples repo](https://github.com/shuttle-hq/shuttle-examples) for many more examples! + diff --git a/examples/serenity.mdx b/examples/serenity.mdx index 6f997e7..940a4b9 100644 --- a/examples/serenity.mdx +++ b/examples/serenity.mdx @@ -100,6 +100,6 @@ tracing = "0.1.37" --- - If you want to explore other frameworks, we have more examples with popular ones like Tower and Warp. You can find them [right here](../examples/other). + - Be sure to check out the [examples repo](https://github.com/shuttle-hq/shuttle-examples) for many more examples! +