mirror of
https://github.com/tokio-rs/axum.git
synced 2026-08-27 00:00:24 +02:00
Revert hello-world example
Was accidentally changed in another PR
This commit is contained in:
@@ -4,58 +4,23 @@
|
|||||||
//! cargo run -p example-hello-world
|
//! cargo run -p example-hello-world
|
||||||
//! ```
|
//! ```
|
||||||
|
|
||||||
|
use axum::{response::Html, routing::get, Router};
|
||||||
|
use std::net::SocketAddr;
|
||||||
|
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
async fn main() {
|
async fn main() {
|
||||||
use axum::async_trait;
|
// build our application with a route
|
||||||
use axum::http::StatusCode;
|
let app = Router::new().route("/", get(handler));
|
||||||
use axum::{
|
|
||||||
extract::{extractor_middleware, FromRequest, RequestParts},
|
|
||||||
routing::{get, post},
|
|
||||||
Router,
|
|
||||||
};
|
|
||||||
|
|
||||||
// An extractor that performs authorization.
|
// run it
|
||||||
struct RequireAuth;
|
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
|
||||||
|
println!("listening on {}", addr);
|
||||||
#[async_trait]
|
axum::Server::bind(&addr)
|
||||||
impl<B> FromRequest<B> for RequireAuth
|
|
||||||
where
|
|
||||||
B: Send,
|
|
||||||
{
|
|
||||||
type Rejection = StatusCode;
|
|
||||||
|
|
||||||
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
|
|
||||||
let auth_header = req
|
|
||||||
.headers()
|
|
||||||
.and_then(|headers| headers.get(axum::http::header::AUTHORIZATION))
|
|
||||||
.and_then(|value| value.to_str().ok());
|
|
||||||
|
|
||||||
if let Some(value) = auth_header {
|
|
||||||
if value == "secret" {
|
|
||||||
return Ok(Self);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Err(StatusCode::UNAUTHORIZED)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn handler() {
|
|
||||||
// If we get here the request has been authorized
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn other_handler() {
|
|
||||||
// If we get here the request has been authorized
|
|
||||||
}
|
|
||||||
|
|
||||||
let app = Router::new()
|
|
||||||
.route("/", get(handler))
|
|
||||||
.route("/foo", post(other_handler))
|
|
||||||
// The extractor will run before all routes
|
|
||||||
.layer(extractor_middleware::<RequireAuth>());
|
|
||||||
|
|
||||||
axum::Server::bind(&"0.0.0.0:3000".parse().unwrap())
|
|
||||||
.serve(app.into_make_service())
|
.serve(app.into_make_service())
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn handler() -> Html<&'static str> {
|
||||||
|
Html("<h1>Hello, World!</h1>")
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user