main.rs
This file
Path
examples/readme/src/main.rs
67 lines · 1.5 KiB · Rust
Last changed by
Fix return types of serve futures (#3601)Jonas Plattebefore adoptionf3a95d7
History of this fileTake it
1//! Run with2//!3//! ```not_rust4//! cargo run -p example-readme5//! ```67use axum::{8 http::StatusCode,9 response::IntoResponse,10 routing::{get, post},11 Json, Router,12};13use serde::{Deserialize, Serialize};1415#[tokio::main]16async fn main() {17 // initialize tracing18 tracing_subscriber::fmt::init();1920 // build our application with a route21 let app = Router::new()22 // `GET /` goes to `root`23 .route("/", get(root))24 // `POST /users` goes to `create_user`25 .route("/users", post(create_user));2627 // run our app with hyper28 let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")29 .await30 .unwrap();31 tracing::debug!("listening on {}", listener.local_addr().unwrap());32 axum::serve(listener, app).await;33}3435// basic handler that responds with a static string36async fn root() -> &'static str {37 "Hello, World!"38}3940async fn create_user(41 // this argument tells axum to parse the request body42 // as JSON into a `CreateUser` type43 Json(payload): Json<CreateUser>,44) -> impl IntoResponse {45 // insert your application logic here46 let user = User {47 id: 1337,48 username: payload.username,49 };5051 // this will be converted into a JSON response52 // with a status code of `201 Created`53 (StatusCode::CREATED, Json(user))54}5556// the input to our `create_user` handler57#[derive(Deserialize)]58struct CreateUser {59 username: String,60}6162// the output to our `create_user` handler63#[derive(Serialize)]64struct User {65 id: u64,66 username: String,67}