mirror of
https://github.com/tokio-rs/axum.git
synced 2025-01-01 08:56:15 +01:00
Example for defining routes and handlers close together (#621)
This commit is contained in:
parent
c50b55384c
commit
ba42783df2
2 changed files with 63 additions and 0 deletions
9
examples/routes-and-handlers-close-together/Cargo.toml
Normal file
9
examples/routes-and-handlers-close-together/Cargo.toml
Normal file
|
@ -0,0 +1,9 @@
|
||||||
|
[package]
|
||||||
|
name = "example-routes-and-handlers-close-together"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2018"
|
||||||
|
publish = false
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
axum = { path = "../../axum" }
|
||||||
|
tokio = { version = "1.0", features = ["full"] }
|
54
examples/routes-and-handlers-close-together/src/main.rs
Normal file
54
examples/routes-and-handlers-close-together/src/main.rs
Normal file
|
@ -0,0 +1,54 @@
|
||||||
|
//! Run with
|
||||||
|
//!
|
||||||
|
//! ```not_rust
|
||||||
|
//! cargo run -p example-routes-and-handlers-close-together
|
||||||
|
//! ```
|
||||||
|
|
||||||
|
use axum::{
|
||||||
|
routing::{get, post, MethodRouter},
|
||||||
|
Router,
|
||||||
|
};
|
||||||
|
use std::net::SocketAddr;
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() {
|
||||||
|
let app = Router::new()
|
||||||
|
.merge(root())
|
||||||
|
.merge(get_foo())
|
||||||
|
.merge(post_foo());
|
||||||
|
|
||||||
|
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
|
||||||
|
println!("listening on {}", addr);
|
||||||
|
axum::Server::bind(&addr)
|
||||||
|
.serve(app.into_make_service())
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn root() -> Router {
|
||||||
|
async fn handler() -> &'static str {
|
||||||
|
"Hello, World!"
|
||||||
|
}
|
||||||
|
|
||||||
|
route("/", get(handler))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_foo() -> Router {
|
||||||
|
async fn handler() -> &'static str {
|
||||||
|
"Hi from `GET /foo`"
|
||||||
|
}
|
||||||
|
|
||||||
|
route("/foo", get(handler))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn post_foo() -> Router {
|
||||||
|
async fn handler() -> &'static str {
|
||||||
|
"Hi from `POST /foo`"
|
||||||
|
}
|
||||||
|
|
||||||
|
route("/foo", post(handler))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn route(path: &str, method_router: MethodRouter) -> Router {
|
||||||
|
Router::new().route(path, method_router)
|
||||||
|
}
|
Loading…
Reference in a new issue