18 unstable releases (3 breaking)

new 0.3.0 Dec 1, 2024
0.2.5 Nov 23, 2024
0.2.4 Oct 19, 2024
0.2.0 Sep 28, 2024
0.0.8 Aug 25, 2024

#1249 in HTTP server

Download history 291/week @ 2024-08-17 192/week @ 2024-08-24 153/week @ 2024-08-31 307/week @ 2024-09-07 269/week @ 2024-09-14 246/week @ 2024-09-21 166/week @ 2024-09-28 313/week @ 2024-10-05 219/week @ 2024-10-12 187/week @ 2024-10-19 32/week @ 2024-10-26 7/week @ 2024-11-02 15/week @ 2024-11-09 43/week @ 2024-11-16 173/week @ 2024-11-23 205/week @ 2024-11-30

437 downloads per month
Used in 2 crates

MIT license

105KB
2K SLoC

crates.io Documentation

Axum is one of the best web frameworks in the Rust community. It is a sub-project based on hyper maintained by Tokio. Axum provides web routing, declarative HTTP request parsing, HTTP response serialization, and can be combined with the middleware in the tower ecosystem.

Dependencies

spring-web = { version = "<version>" }

optional features: http2, multipart, ws.

Configuration items

[web]
binding = "172.20.10.4"  # IP address of the network card to bind, default 0.0.0.0
port = 8000              # Port number to bind, default 8080
connect_info = false     # Whether to use client connection information, default false
graceful = true          # Whether to enable graceful shutdown, default false

# Web middleware configuration
[web.middlewares]
compression = { enable = true }                        # Enable compression middleware
catch_panic = { enable = true }                        # Capture panic generated by handler
logger = { enable = true, level = "info" }             # Enable log middleware
limit_payload = { enable = true, body_limit = "5MB" }  # Limit request body size
timeout_request = { enable = true, timeout = 60000 }   # Request timeout 60s

# Cross-domain configuration
cors = { enable = true, allow_origins = [
    "*.github.io",
], allow_headers = [
    "Authentication",
], allow_methods = [
    "GET",
    "POST",
], max_age = 60 }

# Static resource configuration
static = { enable = true, uri = "/static", path = "static", precompressed = true, fallback = "index.html" }

NOTE: The above middleware configuration can integrate the middleware provided in the tower ecosystem. Of course, if you are very familiar with the tower ecosystem, you can also configure it yourself by writing code without enabling these middleware. The following are relevant document links:

API interface

App implements the WebConfigurator feature, which can be used to specify routing configuration:

use spring::App;
use spring_web::get;
use spring_web::{WebPlugin, WebConfigurator, Router, axum::response::IntoResponse, handler::TypeRouter};
use spring_sqlx::SqlxPlugin;

#[tokio::main]
async fn main() {
    App::new()
      .add_plugin(SqlxPlugin)
      .add_plugin(WebPlugin)
      .add_router(router())
      .run()
      .await
}

fn router() -> Router {
    Router::new().typed_route(hello_word)
}

#[get("/")]
async fn hello_word() -> impl IntoResponse {
   "hello word"
}

You can also use the auto_config macro to implement automatic configuration. This process macro will automatically register the routes marked by the Procedural Macro into the app:

+#[auto_config(WebConfigurator)]
 #[tokio::main]
 async fn main() {
    App::new()
    .add_plugin(SqlxPlugin)
    .add_plugin(WebPlugin)
-   .add_router(router())
    .run()
    .await
}

-fn router() -> Router {
-    Router::new().typed_route(hello_word)
-}

Attribute macro

get in the above example is an attribute macro. spring-web provides eight standard HTTP METHOD process macros: get, post, patch, put, delete, head, trace, options.

You can also use the route macro to bind multiple methods at the same time:

use spring_web::route;
use spring_web::axum::response::IntoResponse;

#[route("/test", method = "GET", method = "HEAD")]
async fn example() -> impl IntoResponse {
    "hello world"
}

In addition, spring also supports binding multiple routes to a handler, which requires the routes attribute macro:

use spring_web::{routes, get, delete};
use spring_web::axum::response::IntoResponse;

#[routes]
#[get("/test")]
#[get("/test2")]
#[delete("/test")]
async fn example() -> impl IntoResponse {
    "hello world"
}

Extract the Component registered by the plugin

In the above example, the SqlxPlugin plugin automatically registers a Sqlx connection pool component for us. We can use Component to extract this connection pool from State. Component is an axum extractor.

use anyhow::Context;
use spring_web::get;
use spring_web::{axum::response::IntoResponse, extractor::Component, error::Result};
use spring_sqlx::{ConnectPool, sqlx::{self, Row}};

#[get("/version")]
async fn mysql_version(Component(pool): Component<ConnectPool>) -> Result<String> {
    let version = sqlx::query("select version() as version")
        .fetch_one(&pool)
        .await
        .context("sqlx query failed")?
        .get("version");
    Ok(version)
}

Axum also provides other extractors, which are reexported under spring_web::extractor.

Read configuration

You can use Config to extract the configuration in the toml file.

use spring_web::get;
use spring_web::{extractor::Config, axum::response::IntoResponse};
use spring::config::Configurable;
use serde::Deserialize;

#[derive(Debug, Configurable, Deserialize)]
#[config_prefix = "custom"]
struct CustomConfig {
    a: u32,
    b: bool,
}

#[get("/config")]
async fn use_toml_config(Config(conf): Config<CustomConfig>) -> impl IntoResponse {
    format!("a={}, b={}", conf.a, conf.b)
}

Add the corresponding configuration to your configuration file:

[custom]
a = 1
b = true

Complete code reference web-example

Use Extractor in Middleware

You can also use Extractor in middleware, but please note that you need to follow the rules of axum.

use spring_web::{axum::{response::Response, middleware::Next}, extractor::{Request, Component}};
use spring_sqlx::ConnectPool;

async fn problem_middleware(Component(db): Component<ConnectPool>, request: Request, next: Next) -> Response {
    // do something
    let response = next.run(request).await;

    response
}

Complete code reference web-middleware-example

Dependencies

~14–26MB
~380K SLoC