spring-web 0.4.16

Integration of rust application framework spring-rs and Axum web framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
[![crates.io](https://img.shields.io/crates/v/spring-web.svg)](https://crates.io/crates/spring-web)
[![Documentation](https://docs.rs/spring-web/badge.svg)](https://docs.rs/spring-web)

[Axum](https://github.com/tokio-rs/axum) is one of the best web frameworks in the Rust community. It is a sub-project based on [hyper](https://github.com/hyperium/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](https://github.com/tower-rs) ecosystem.

## Dependencies

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

optional **features**:
* `http2`: http2
* `multipart`: file upload
* `ws`: websocket
* `socket_io`: SocketIO support
* `openapi`: OpenAPI documentation
* `openapi-redoc`: Redoc documentation interface
* `openapi-scalar`: Scalar documentation interface
* `openapi-swagger`: Swagger documentation interface

## Configuration items

```toml
[web]
binding = "172.20.10.4"  # IP address of the network interface 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
global_prefix = "api"    # Global prefix for all routes, default empty

# 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 = [
    "https://spring-rs.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:
> * [tower]https://docs.rs/tower/latest/tower/
> * [tower-http]https://docs.rs/tower-http/latest/tower_http/

## API interface

App implements the [WebConfigurator](https://docs.rs/spring-web/latest/spring_web/trait.WebConfigurator.html) feature, which can be used to specify routing configuration:

```no_run, rust, linenos, hl_lines=6 10-18
use spring::App;
use spring_web::{get, get_api};
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"
}

/// # The API summary title must use the head-1 in Markdown format.
/// description
/// description support multi line
/// The get_api macro automatically collects the request parameters and response schema.
/// @tag api_tag
#[get_api("/api")]
async fn hello_api() -> String {
   "hello api".to_string()
}
```

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:

```diff
+#[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

In the example above, `get` is an attribute macro. `spring-web` provides procedural macros for eight standard HTTP methods: `get`, `post`, `patch`, `put`, `delete`, `head`, `trace`, and `options`. It also provides eight macros for generating OpenAPI documentation, such as `get_api` and `post_api`.

You can also use the `route` or `api_route` macros to bind multiple methods simultaneously:

```rust
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`](https://docs.rs/spring-macros/latest/spring_macros/attr.routes.html) attribute macro:

```rust
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`](https://docs.rs/spring-web/latest/spring_web/extractor/struct.Component.html) is an axum [extractor](https://docs.rs/axum/latest/axum/extract/index.html).

```rust
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](https://docs.rs/axum/latest/axum/extract/index.html), which are reexported under [`spring_web::extractor`](https://docs.rs/spring-web/latest/spring_web/extractor/index.html).

## Read configuration

You can use [`Config`](https://docs.rs/spring-web/latest/spring_web/extractor/struct.Config.html) to extract the configuration in the toml file.


```rust
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:

```toml
[custom]
a = 1
b = true
```

Complete code reference [`web-example`][web-example]

[web-example]: https://github.com/spring-rs/spring-rs/tree/master/examples/web-example

## Use Extractor in Middleware

You can also use [Extractor in middleware](https://docs.rs/axum/latest/axum/middleware/fn.from_fn.html), but please note that you need to follow the rules of axum.

```rust
use spring_web::{middlewares, axum::middleware};

/// you can apply this middleware to your routes using the `middlewares` macro:
#[middlewares(
    middleware::from_fn(problem_middleware),
)]
mod routes {
    use spring_web::{axum::{response::Response, middleware::Next, response::IntoResponse}, extractor::{Request, Component}};
    use spring_sqlx::ConnectPool;
    use spring_web::{middlewares, get, axum::middleware};
    use std::time::Duration;

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

        response
    }

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

}
```

This middleware will:
- Intercept all responses from routes in the module

Complete code reference [`web-middleware-example`][web-middleware-example]

[web-middleware-example]: https://github.com/spring-rs/spring-rs/tree/master/examples/web-middleware-example

spring-web is a thin wrapper around axum, adding some macros to simplify development. [The examples of axum](https://github.com/tokio-rs/axum/tree/main/examples) can be run in spring-web.

# SocketIO support

You can enable the `socket_io` feature of `spring-web` to use a integration with [socketioxide](https://github.com/Totodore/socketioxide).

SocketIO is a implementation of WebSocket with more definitions.
- Named events (like `chat message`, `user joined`, etc.) instead of just plain messages
- Automatic reconnection if the connection is lost
- Heartbeat mechanism to detect dead connections
- Rooms / Namespaces to group clients
- Fallbacks to other transports if WebSocket isn't available

You can refer to the [socketio-example](https://github.com/spring-rs/spring-rs/tree/master/examples/web-socketio-example) for a example of using SocketIO in spring-web.

We can share components registered by plugins in SocketIO handlers, just like in normal HTTP handlers, for example, using the Sqlx connection pool component registered by the `SqlxPlugin` plugin.


# OpenAPI support

You can enable the `openapi` feature of `spring-web` to use OpenAPI documentation generation. You can refer to the [openapi-example](https://github.com/spring-rs/spring-rs/tree/master/examples/openapi-example) for more information.

Besides you need to enable one of the documentation interface features: `openapi-redoc`, `openapi-scalar` or `openapi-swagger` to generate the corresponding documentation interface.

```rust,ignore
/// Always return error  
/// 
/// This endpoint is annotated with status_codes for Errors::B and Errors::C
/// @tag error
/// @status_codes Errors::B, Errors::C, Errors::SqlxError, Errors::TeaPod
#[get_api("/error")]
async fn error() -> Result<Json<String>, Errors> {
    Err(Errors::B)
}
```

To generate OpenAPI documentation, you can use the `get_api`, `post_api`, etc. macros to define your API endpoints. These macros will automatically collect request parameters and response schemas to generate OpenAPI documentation.

The comments above the API function are used to provide additional information for the OpenAPI documentation, such as tags and status codes.

The status_codes annotation specifies the possible error types that the API may return. This information will be included in the OpenAPI documentation, allowing users to understand the potential error responses when calling this API.

In case of want to define custom error types, you must implement the `HttpStatusCode` trait for your error type, which is used to map the error to an HTTP status code in the OpenAPI documentation.

We can use the derive macro `ProblemDetails` to automatically implement both the `HttpStatusCode` and `ToProblemDetails` traits for our custom error type.

In this case we are implementing `thiserror::Error` for better error handling, but it's not mandatory.

```rust,ignore
use spring_web::ProblemDetails;
use spring_web::axum::http::StatusCode;

#[derive(thiserror::Error, Debug, ProblemDetails)]
pub enum CustomErrors {
    #[status_code(400)]
    #[error("A basic error occurred")]
    ABasicError,

    #[status_code(500)]
    #[error(transparent)]
    SqlxError(#[from] spring_sqlx::sqlx::Error),

    #[status_code(418)]
    #[error("TeaPod error occurred: {0:?}")]
    TeaPod(CustomErrorSchema),
}

#[derive(Debug, JsonSchema)]
pub struct CustomErrorSchema {
    pub code: u16,
    pub message: String,
}
```

## Simplified Error Handling with Automatic Problem Details

The `ProblemDetails` derive macro automatically generates both `HttpStatusCode` and `ToProblemDetails` implementations, eliminating the need for manual mapping:

```rust,ignore
use spring_web::ProblemDetails;

// Only need ProblemDetails derive - HttpStatusCode and ToProblemDetails are generated automatically!
#[derive(thiserror::Error, Debug, ProblemDetails)]
pub enum ApiErrors {
    // Basic usage - uses about:blank as problem type
    #[status_code(400)]
    #[error("Validation failed")]
    ValidationError,

    // Custom problem type with full URI
    #[status_code(401)]
    #[problem_type("https://api.myapp.com/problems/authentication-required")]
    #[error("Authentication required")]
    AuthenticationError,

    // Custom problem type with all fields
    #[status_code(404)]
    #[problem_type("https://api.myapp.com/problems/resource-not-found")]
    #[title("Resource Not Found")]
    #[detail("The requested resource could not be found")]
    #[error("Resource not found")]
    NotFoundError,
}

impl IntoResponse for ApiErrors {
    fn into_response(self) -> Response {
        // Both HttpStatusCode and ToProblemDetails are automatically implemented!
        self.to_problem_details().into_response()
    }
}
```

The macro automatically maps common HTTP status codes to appropriate Problem Details:
- `400``ProblemDetails::validation_error()` (uses `about:blank`)
- `401``ProblemDetails::authentication_error()` (uses `about:blank`)
- `403``ProblemDetails::authorization_error()` (uses `about:blank`)
- `404``ProblemDetails::not_found()` (uses `about:blank`)
- `500``ProblemDetails::internal_server_error()` (uses `about:blank`)
- `503``ProblemDetails::service_unavailable()` (uses `about:blank`)
- Other codes → Uses `about:blank` as problem type

## Advanced Problem Details with Custom Attributes

The `ProblemDetails` derive macro supports additional attributes for fine-grained control over the generated Problem Details:

```rust,ignore
use spring_web::ProblemDetails;

#[derive(thiserror::Error, Debug, ProblemDetails)]
pub enum ApiError {
    // Basic usage - auto-generated fields
    #[status_code(400)]
    #[error("Validation failed")]
    BasicValidation,

    // Custom problem type and title
    #[status_code(400)]
    #[problem_type("https://api.myapp.com/problems/field-validation")]
    #[title("Field Validation Error")]
    #[error("Field validation failed")]
    FieldValidation,

    // Full customization
    #[status_code(403)]
    #[problem_type("https://api.myapp.com/problems/insufficient-permissions")]
    #[title("Insufficient Permissions")]
    #[detail("You need admin privileges to perform this action")]
    #[instance("/admin/users")]
    #[error("Access denied")]
    InsufficientPermissions,
}
```

### Supported Attributes

- `#[status_code(code)]` - **Required**: HTTP status code
- `#[problem_type("uri")]` - **Optional**: Custom problem type URI
- `#[title("title")]` - **Optional**: Custom problem title
- `#[detail("detail")]` - **Optional**: Custom problem detail message  
- `#[instance("uri")]` - **Optional**: Problem instance URI

### Title Compatibility

The `title` field can be automatically derived from the `#[error("...")]` attribute if no explicit `#[title("...")]` is provided. This provides compatibility with `thiserror::Error` and reduces duplication:

```rust,ignore
#[derive(thiserror::Error, Debug, ProblemDetails)]
pub enum ApiError {
    // Title explicitly set
    #[status_code(400)]
    #[title("Custom Validation Error")]
    #[error("Validation failed")]
    ExplicitTitle,
    
    // Title derived from error attribute
    #[status_code(422)]
    #[detail("Request data is invalid")]
    #[error("Validation Failed")]  // This becomes the title
    ImplicitTitle,
}
```

### Generated Response Examples

**BasicValidation** (auto-generated):
```json
{
  "type": "about:blank/basic-validation",
  "title": "Basic Validation Error",
  "status": 400,
  "detail": "BasicValidation occurred"
}
```

**InsufficientPermissions** (fully customized):
```json
{
  "type": "https://api.myapp.com/problems/insufficient-permissions",
  "title": "Insufficient Permissions",
  "status": 403,
  "detail": "You need admin privileges to perform this action",
  "instance": "/admin/users"
}
```

```rust,ignore
#[tokio::main]
async fn main() {
    App::new()
        .add_plugin(WebPlugin)
        .run()
        .await;
}
```

Then implement error handling:

```rust,ignore
use spring_web::ProblemDetails;

#[derive(thiserror::Error, Debug, ProblemDetails)]
pub enum CustomErrors {
    // Basic usage - uses about:blank as problem type
    #[status_code(400)]
    #[error("A basic error occurred")]
    ABasicError,

    // Custom problem type
    #[status_code(500)]
    #[problem_type("https://api.myapp.com/problems/database-error")]
    #[error(transparent)]
    SqlxError(#[from] spring_sqlx::sqlx::Error),

    #[status_code(418)]
    #[error("TeaPod error occurred: {0:?}")]
    TeaPod(CustomErrorSchema),
}

// Implement Problem Details conversion
impl ToProblemDetails for CustomErrors {
    fn to_problem_details(&self) -> ProblemDetails {
        match self {
            CustomErrors::ABasicError => {
                ProblemDetails::validation_error("A basic validation error occurred")
            }
            CustomErrors::SqlxError(err) => {
                ProblemDetails::custom_problem(
                    "database-error",
                    "Database Error", 
                    500,
                ).with_detail(format!("Database operation failed: {}", err))
            }
            CustomErrors::TeaPod(schema) => {
                ProblemDetails::custom_problem(
                    "teapot-error",
                    "I'm a teapot",
                    418,
                ).with_detail(format!("TeaPod error: {}", schema.message))
            }
        }
    }
}

impl IntoResponse for CustomErrors {
    fn into_response(self) -> Response {
        self.to_problem_details().into_response()
    }
}
```

The Problem Details response will be formatted as:

```json
{
  "type": "https://api.myapp.com/problems/validation-error",
  "title": "Validation Error",
  "status": 400,
  "detail": "A basic validation error occurred"
}
```

### Automatic Instance URI Capture

Problem Details automatically captures the current request URI and includes it in the `instance` field. This feature is enabled by default and requires no additional configuration:

```rust,ignore
// No middleware configuration needed - it's automatic!

#[get_api("/users/{id}")]
async fn get_user(Path(id): Path<u32>) -> Result<Json<User>, ApiError> {
    if id == 999 {
        // The instance field will automatically be set to "/users/999"
        return Err(ApiError::NotFound);
    }
    
    Ok(Json(User { id, name: "User".to_string() }))
}
```

This will automatically generate responses with the request URI:

```json
{
  "type": "about:blank",
  "title": "Resource Not Found",
  "status": 404,
  "detail": "The requested resource was not found",
  "instance": "/users/999"
}
```