sword/lib.rs
1//! # Sword - Rust Web Framework
2//!
3//! Sword is a modern, fast, and ergonomic web framework for Rust, built on top of [Axum](https://github.com/tokio-rs/axum).
4//! It provides a clean API, powerful middleware system, and built-in features for rapid web development.
5//!
6//! ## π Quick Start
7//!
8//! ```rust,no_run
9//! use sword::prelude::*;
10//!
11//! #[controller("/api")]
12//! struct ApiController;
13//!
14//! #[routes]
15//! impl ApiController {
16//! #[get("/hello")]
17//! async fn hello() -> HttpResponse {
18//! HttpResponse::Ok().message("Hello, World!")
19//! }
20//! }
21//!
22//! #[sword::main]
23//! async fn main() {
24//! let app = Application::builder()?
25//! .with_controller::<ApiController>()
26//! .build();
27//!
28//! app.run().await?;
29//! }
30//! ```
31//!
32//! ## π― Core Features
33//!
34//! - **π£οΈ Macro-based routing** - Clean and intuitive route definitions using `#[get]`, `#[post]`, etc.
35//! - **π JSON-first design** - Built-in JSON serialization/deserialization support
36//! - **β
Request validation** - Automatic validation using `serde` and `validator` crates
37//! - **π RFC-compliant HTTP responses** - Standards-compliant HTTP handling
38//! - **πΈοΈ Express-like Context** - Rich request context with utility methods
39//! - **π Dependency Injection** - Optional DI support using `shaku` crate
40//! - **π§© Middleware system** - Flexible middleware at route and controller levels
41//! - **π Async by default** - Built on `tokio` and `axum` for high performance
42//!
43//! ## π¦ Optional Features
44//!
45//! Enable additional functionality by adding features to your `Cargo.toml`:
46//!
47//! ```toml
48//! [dependencies]
49//! sword = { version = "0.1.7", features = ["cookies", "multipart", "helmet"] }
50//! ```
51//!
52//! Available features:
53//! - `multipart` - File upload support
54//! - `cookies` - Cookie handling
55//! - `helmet` - Security headers middleware
56//! - `shaku-di` - Dependency injection
57//!
58//! ## π Examples
59//!
60//! Check out the comprehensive examples in the [repository](https://github.com/sword-framework/sword/tree/main/examples):
61//!
62//! - **Basic server** - Simple HTTP server setup
63//! - **Middleware** - Custom middleware implementation
64//! - **Data validation** - Request validation examples
65//! - **File uploads** - Multipart form handling
66//! - **Dependency injection** - DI patterns
67//! - **State management** - Shared application state
68
69mod validation;
70
71/// The prelude module contains the most commonly used items from the Sword framework.
72///
73/// This module is designed to be imported with a glob import to bring all essential
74/// types and traits into scope for typical Sword applications.
75///
76/// ### Example
77///
78/// ```rust,ignore
79/// use sword::prelude::*;
80///
81/// // Now you have access to Application, Context, HttpResult, and more
82/// ```
83pub mod prelude {
84 pub use crate::core::{Application, ApplicationConfig};
85 pub use crate::core::{ConfigItem, config};
86
87 pub use crate::errors::{ApplicationError, RequestError, StateError};
88 pub use crate::web::*;
89
90 #[cfg(feature = "cookies")]
91 pub use crate::web::cookies::*;
92
93 #[cfg(feature = "multipart")]
94 pub use crate::web::multipart;
95}
96
97/// Error types and error handling utilities.
98///
99/// This module defines the error types used throughout the Sword framework:
100///
101/// - [`ApplicationError`](errors::ApplicationError) - Errors during application startup and runtime
102/// - [`RequestError`](errors::RequestError) - Errors during request processing and validation
103/// - [`StateError`](errors::StateError) - Errors when accessing application state
104/// - [`ConfigError`](errors::ConfigError) - Configuration-related errors
105///
106/// All errors implement the standard `Error` trait and provide detailed error messages
107/// for debugging and logging purposes.
108///
109/// ## Error Handling Patterns
110///
111/// ```rust,ignore
112/// use sword::prelude::*;
113///
114/// #[get("/users/:id")]
115/// async fn get_user(ctx: Context) -> HttpResult<HttpResponse> {
116/// // This returns a RequestError if parsing fails
117/// let user_id = ctx.param::<u32>("id")?;
118///
119/// // This returns a StateError if state not found
120/// let db = ctx.get_state::<Database>()?;
121///
122/// Ok(HttpResponse::Ok().data(user_id))
123/// }
124/// ```
125pub mod errors;
126
127/// Core framework components for application setup and configuration.
128///
129/// This module contains the fundamental building blocks of a Sword application:
130///
131/// - [`Application`](core::Application) - The main application struct that manages routing and configuration
132/// - [`ApplicationConfig`](core::ApplicationConfig) - Configuration structure for application settings
133/// - [`Config`](core::Config) - Configuration management with file and environment variable support
134/// - [`State`](core::State) - Thread-safe state container for sharing data across requests
135///
136/// ## Example
137///
138/// ```rust,ignore
139/// use sword::prelude::*;
140///
141/// // Create and configure an application
142/// let app = Application::builder()?
143/// .with_controller::<MyController>()
144/// .build();
145///
146/// // Access configuration
147/// let config = app.config.get::<ApplicationConfig>()?;
148/// ```
149pub mod core {
150 mod application;
151 mod config;
152 mod router;
153 mod state;
154 mod utils;
155
156 pub use router::RouterProvider;
157 pub use utils::deserialize_size;
158
159 pub use application::{Application, ApplicationConfig};
160 pub use config::{Config, ConfigItem, config};
161 pub use state::State;
162}
163
164/// Web-related components for handling HTTP requests and responses.
165///
166/// This module provides the core web functionality including:
167///
168/// - [`Context`](web::Context) - Request context containing parameters, headers, body, and utilities
169/// - [`Middleware`](web::Middleware) - Trait for implementing custom middleware
170/// - HTTP types and utilities from Axum
171/// - Routing macros: `#[controller]`, `#[get]`, `#[post]`, etc.
172///
173/// ## Key Features
174///
175/// ### Request Handling
176/// - Parameter extraction from URL and query strings
177/// - JSON request/response handling
178/// - Header manipulation
179/// - Request validation
180///
181/// ### Middleware System
182/// - Route-level middleware with `#[middleware(MyMiddleware)]`
183/// - Controller-level middleware
184/// - Built-in middleware for common tasks
185///
186/// ### Optional Features
187/// - **Cookies** - Cookie handling with signed/private support (feature: `cookies`)
188/// - **Multipart** - File upload support (feature: `multipart`)
189///
190/// ## Example
191///
192/// ```rust,no_run
193/// use sword::web::*;
194///
195/// #[controller("/api")]
196/// struct ApiController;
197///
198/// #[routes]
199/// impl ApiController {
200/// #[get("/users/:id")]
201/// async fn get_user(ctx: Context) -> HttpResult<HttpResponse> {
202/// let user_id = ctx.param::<u32>("id")?;
203/// // ... fetch user logic
204/// Ok(HttpResponse::Ok().message(format!("User {}", user_id)))
205/// }
206/// }
207/// ```
208pub mod web {
209
210 mod context;
211 mod middleware;
212
213 pub use axum::http::{Method, StatusCode, header};
214 pub use axum_responses::Result as HttpResult;
215 pub use axum_responses::http::*;
216 pub use sword_macros::{controller, delete, get, patch, post, put, routes};
217
218 pub use crate::next;
219 pub use context::{Context, request::RequestValidation};
220 pub use middleware::*;
221
222 #[cfg(feature = "multipart")]
223 pub use context::multipart;
224
225 #[cfg(feature = "cookies")]
226 pub use context::cookies;
227}
228
229pub use sword_macros::main;
230
231#[doc(hidden)]
232pub mod __internal {
233 pub use axum::extract::{FromRequest, FromRequestParts, Request as AxumRequest};
234 pub use axum::middleware::Next as AxumNext;
235 pub use axum::middleware::from_fn_with_state as mw_with_state;
236 pub use axum::response::{IntoResponse, Response as AxumResponse};
237 pub use axum::routing::Router as AxumRouter;
238 pub use axum::routing::{
239 delete as axum_delete_fn, get as axum_get_fn, patch as axum_patch_fn,
240 post as axum_post_fn, put as axum_put_fn,
241 };
242
243 pub use tokio::runtime as tokio_runtime;
244}