3个版本
新版本 0.0.7 | 2024年8月21日 |
---|---|
0.0.6 | 2024年8月17日 |
0.0.4 | 2024年8月7日 |
#489 in HTTP服务器
270每月下载次数
在spring-actuator中使用
56KB
1K SLoC
依赖关系
spring-web = { version = "0.0.7" }
配置项
[web]
binding = "172.20.10.4" # IP address of the network card to bind, default 127.0.0.1
port = 8000 # Port number to bind, default 8080
# Web middleware configuration
[web.middlewares]
compression = { enable = true } # Enable compression middleware
logger = { enable = true } # Enable log middleware
catch_panic = { enable = true } # Capture panic generated by handler
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" }
API接口
应用实现了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)
+}
+#[get("/")]
+async fn hello_word() -> impl IntoResponse {
+ "hello word"
+}
您还可以使用auto_config
宏来自动配置。此过程宏会自动将由过程宏标记的路由注册到应用中
+#[auto_config(WebConfigurator)]
#[tokio::main]
async fn main() {
App::new()
.add_plugin(SqlxPlugin)
.add_plugin(WebPlugin)
- .add_router(router())
.run()
.await
}
属性宏
get
在上面的示例中是一个属性宏。Spring提供八个标准HTTP方法过程宏:get
、post
、patch
、put
、delete
、head
、trace
、options
。
您还可以使用route
宏同时绑定多个方法
#[route("/test", method = "GET", method = "HEAD")]
async fn example() -> impl IntoResponse {
"hello world"
}
此外,spring还支持将多个路由绑定到处理器,需要使用routes
属性宏
#[routes]
#[get("/test")]
#[get("/test2")]
#[delete("/test")]
async fn example() -> impl IntoResponse {
"hello world"
}
提取由插件注册的组件
在上面的示例中,SqlxPlugin
插件为我们自动注册了一个Sqlx连接池组件。我们可以使用Component
从State中提取此连接池。Component
是axum的一个提取器。
use spring::get;
use spring_sqlx::{sqlx::{self, Row}, ConnectPool};
use spring_web::extractor::Component;
use spring_web::error::Result;
use anyhow::Context;
#[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还提供了其他提取器,它们在spring_web::extractor
下重新导出。
完整代码参考 web-example
依赖关系
~12–21MB
~282K SLoC