Go to file
David Pedersen f67abd1ee2
Add extractor for remote connection info (#55)
Fixes https://github.com/tokio-rs/axum/issues/43

With this you can get the remote address like so:

```rust
use axum::{prelude::*, extract::ConnectInfo};
use std::net::SocketAddr;

let app = route("/", get(handler));

async fn handler(ConnectInfo(addr): ConnectInfo<SocketAddr>) -> String {
    format!("Hello {}", addr)
}

// Starting the app with `into_make_service_with_connect_info` is required
// for `ConnectInfo` to work.
let make_svc = app.into_make_service_with_connect_info::<SocketAddr, _>();

hyper::Server::bind(&"0.0.0.0:3000".parse().unwrap())
    .serve(make_svc)
    .await
    .expect("server failed");
```

This API is fully generic and supports whatever transport layer you're using with Hyper. I've updated the unix domain socket example to extract `peer_creds` and `peer_addr`.
2021-07-31 21:36:30 +02:00
.github Update links 2021-07-22 19:39:08 +02:00
examples Add extractor for remote connection info (#55) 2021-07-31 21:36:30 +02:00
src Add extractor for remote connection info (#55) 2021-07-31 21:36:30 +02:00
.gitignore Initial pile of hacks 2021-05-29 21:13:06 +02:00
CHANGELOG.md Add extractor for remote connection info (#55) 2021-07-31 21:36:30 +02:00
CONTRIBUTING.md Update links 2021-07-22 19:39:08 +02:00
Cargo.toml Add extractor for remote connection info (#55) 2021-07-31 21:36:30 +02:00
LICENSE Misc repo setup (#7) 2021-06-12 20:18:21 +02:00
README.md Mention benchmark in readme 2021-07-31 14:53:12 +02:00
askama.toml Add HTML template example (#17) 2021-06-13 13:58:12 +02:00
deny.toml Generic request body (#22) 2021-06-19 12:50:33 +02:00

README.md

axum

axum is a web application framework that focuses on ergonomics and modularity.

Build status Crates.io Documentation

More information about this crate can be found in the crate documentation.

High level features

  • Route requests to handlers with a macro free API.
  • Declaratively parse requests using extractors.
  • Simple and predictable error handling model.
  • Generate responses with minimal boilerplate.
  • Take full advantage of the tower and tower-http ecosystem of middleware, services, and utilities.

In particular the last point is what sets axum apart from other frameworks. axum doesn't have its own middleware system but instead uses tower::Service. This means axum gets timeouts, tracing, compression, authorization, and more, for free. It also enables you to share middleware with applications written using hyper or tonic.

Usage example

use axum::{prelude::*, response::IntoResponse};
use http::StatusCode;
use serde::{Deserialize, Serialize};
use std::net::SocketAddr;

#[tokio::main]
async fn main() {
    // build our application with a route
    let app =
        // `GET /` goes to `root`
        route("/", get(root))
        // `POST /users` goes to `create_user`
        .route("/users", post(create_user));

    // run our app with hyper
    let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
    tracing::debug!("listening on {}", addr);
    hyper::Server::bind(&addr)
        .serve(app.into_make_service())
        .await
        .unwrap();
}

// basic handler that responds with a static string
async fn root() -> &'static str {
    "Hello, World!"
}

async fn create_user(
    // this argument tells axum to parse the request body
    // as JSON into a `CreateUser` type
    extract::Json(payload): extract::Json<CreateUser>,
) -> impl IntoResponse {
    // insert your application logic here
    let user = User {
        id: 1337,
        username: payload.username,
    };

    // this will be converted into an JSON response
    // with a status code of `201 Created`
    (StatusCode::CREATED, response::Json(user))
}

// the input to our `create_user` handler
#[derive(Deserialize)]
struct CreateUser {
    username: String,
}

// the output to our `create_user` handler
#[derive(Serialize)]
struct User {
    id: u64,
    username: String,
}

See the crate documentation for way more examples.

Performance

axum is a relatively thin layer on top of hyper and adds very little overhead. So axum's performance is comparable to hyper. You can find a benchmark here.

Examples

The examples folder contains various examples of how to use axum. The docs also have lots of examples

Getting Help

In the axum's repo we also have a number of examples showing how to put everything together. You're also welcome to ask in the Discord channel or open an issue with your question.

Contributing

🎈 Thanks for your help improving the project! We are so happy to have you! We have a contributing guide to help you get involved in the axum project.

License

This project is licensed under the MIT license.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in axum by you, shall be licensed as MIT, without any additional terms or conditions.