ripress 2.5.1

An Express.js-inspired web framework for Rust
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
#![warn(missing_docs)]

//! # Ripress
//!
//! Ripress is a lightweight, modular web framework for building HTTP APIs and web applications in Rust.
//! It provides a simple and flexible API for defining routes, handling requests and responses, and composing middleware.
//! Inspired by Express.js, Ripress brings the familiar developer experience to Rust while maintaining high performance.
//!
//! ## Quick Start
//!
//! ```no_run
//! use ripress::{app::App, types::RouterFns, req::HttpRequest};
//!
//! #[tokio::main]
//! async fn main() {
//!     let mut app = App::new();
//!
//!     // Define routes
//!     app.get("/", |_req: HttpRequest, res| async move {
//!         res.ok().text("Hello, World!")
//!     });
//!
//!     app.get("/api/users", |_req: HttpRequest, res| async move {
//!         res.ok().json(serde_json::json!({
//!             "users": ["Alice", "Bob", "Charlie"]
//!         }))
//!     });
//!
//!     // Add middleware
//!     app.use_cors(None);
//!
//!     // Start server
//!     app.listen(3000, || {
//!         println!("Server running on http://localhost:3000");
//!     }).await;
//! }
//! ```
//!
//! ## Key Features
//!
//! - **Express.js-like API**: Familiar routing and middleware patterns
//! - **Async/Await Support**: Built on Tokio for high-performance async operations
//! - **Type Safety**: Full Rust type safety with compile-time error checking
//! - **Built-in Middleware**: CORS, logging, compression, rate limiting, and more
//! - **Request/Response Objects**: Rich APIs for handling HTTP data
//! - **WebSocket Support**: Real-time communication via the `wynd` crate (optional `with-wynd` feature)
//! - **Static File Serving**: Built-in support for serving static assets
//!
//! ## Optional Features
//!
//! Several features are optional and can be enabled to reduce compile time and binary size:
//!
//! - **`compression`**: Response compression middleware (gzip/deflate)
//! - **`file-upload`**: File upload middleware for multipart form data
//! - **`logger`**: Request/response logging middleware
//! - **`with-wynd`**: WebSocket support via the `wynd` crate
//!
//! ## Advanced Examples
//!
//! ### RESTful API with JSON
//! ```no_run
//! use ripress::{app::App, types::RouterFns, req::HttpRequest};
//! use serde::{Deserialize, Serialize};
//!
//! #[derive(Serialize, Deserialize)]
//! struct User {
//!     id: u32,
//!     name: String,
//!     email: String,
//! }
//!
//! #[tokio::main]
//! async fn main() {
//!     let mut app = App::new();
//!
//!     // GET /users - List all users
//!     app.get("/users", |_req: HttpRequest, res| async move {
//!         let users = vec![
//!             User { id: 1, name: "Alice".to_string(), email: "alice@example.com".to_string() },
//!             User { id: 2, name: "Bob".to_string(), email: "bob@example.com".to_string() },
//!         ];
//!         res.ok().json(users)
//!     });
//!
//!     // POST /users - Create a new user
//!     app.post("/users", |req: HttpRequest, res| async move {
//!         match req.json::<User>() {
//!             Ok(user) => res.created().json(user),
//!             Err(_) => res.bad_request().text("Invalid JSON"),
//!         }
//!     });
//!
//!     // GET /users/:id - Get user by ID
//!     app.get("/users/:id", |req: HttpRequest, res| async move {
//!         let user_id = req.params.get("id").unwrap_or("0");
//!         res.ok().json(serde_json::json!({
//!             "id": user_id,
//!             "message": "User found"
//!         }))
//!     });
//!
//!     app.listen(3000, || {
//!         println!("API server running on http://localhost:3000");
//!     }).await;
//! }
//! ```
//!
//! ### File Upload with Middleware
//! ```ignore
//! use ripress::{app::App, middlewares::file_upload::file_upload, types::RouterFns, req::HttpRequest};
//!
//! #[tokio::main]
//! async fn main() {
//!     let mut app = App::new();
//!
//!     // Add file upload middleware
//!     app.use_pre_middleware("/upload", file_upload(None));
//!
//!     app.post("/upload", |req: HttpRequest, res| async move {
//!         // Access uploaded files through request data
//!         if let Some(file_data) = req.get_data("uploaded_file") {
//!             res.ok().text(format!("File uploaded: {}", file_data))
//!         } else {
//!             res.bad_request().text("No file uploaded")
//!         }
//!     });
//!
//!     app.listen(3000, || {
//!         println!("File upload server running on http://localhost:3000");
//!     }).await;
//! }
//! ```
//!
//! # Validation and Extraction based implementation
//!
//! Ripress provides a powerful and flexible way to handle request data extraction and validation. It supports various types of data extraction, including route parameters, query parameters, JSON bodies, and request meta data. The framework also provides a set of macros and traits for easily implementing custom extraction and validation logic.
//!
//! ## Example
//!
//! ```ignore
//! use ripress::{
//!     app::App,
//!     req::{
//!         body::json_data::{JsonBody, JsonBodyValidated},
//!         query_params::QueryParam,
//!         request_headers::Headers,
//!         route_params::Params,
//!     },
//!     types::RouterFns,
//! };
//! use ripress_derive::{FromJson, FromParams, FromQueryParam};
//! use serde::{Deserialize, Serialize};
//! use validator::Validate;
//!
//! #[derive(FromJson, Deserialize, Debug, Serialize)]
//! struct User {
//!     username: String,
//! }
//!
//! #[derive(FromJson, Deserialize, Validate, Debug)]
//! struct Signup {
//!     #[validate(length(min = 3))]
//!     username: String,
//!     #[validate(email)]
//!     email: String,
//! }
//!
//! #[derive(Deserialize, Debug, FromQueryParam)]
//! struct PageQuery {
//!     page: u32,
//! }
//!
//! #[derive(Deserialize, Debug, FromParams)]
//! struct PathParams {
//!     id: String,
//! }
//!
//! #[derive(FromParams)]
//! struct OrgParams {
//!     org_id: String,
//!     user_id: String,
//! }
//!
//! #[derive(FromQueryParam)]
//! struct OrgQueryParams {
//!     query: String,
//! }
//!
//! #[tokio::main]
//! async fn main() {
//!     let mut app = App::new();
//!
//!     // Classic JsonBody extractor (not validated)
//!     app.post("/json", |body: JsonBody<User>, res| async move {
//!         let username = &body.username;
//!         println!("Classic JsonBody: {}", username);
//!         res.ok().json(body)
//!     });
//!
//!     // ValidatedJson extractor - performs validation on deserialization
//!     app.post(
//!         "/signup",
//!         |body: JsonBodyValidated<Signup>, res| async move {
//!             println!("Email: {}, Username: {}", body.email, body.username);
//!             res.ok().json(serde_json::json!({
//!                 "msg": "Signup received",
//!                 "user": &body.username,
//!                 "email": &body.email
//!             }))
//!         },
//!     );
//!
//!     // Query string extractor
//!     app.get(
//!         "/articles",
//!         |query: QueryParam<PageQuery>, res| async move {
//!             let page = query.page;
//!             res.ok().json(serde_json::json!({ "page": page }))
//!         },
//!     );
//!
//!     // Path param extractor
//!     app.get("/user/:id", |params: Params<PathParams>, res| async move {
//!         println!("Path params: id: {:?}", params.id);
//!         res.ok().json(serde_json::json!({ "id": params.id }))
//!     });
//!
//!     // Mixing extractors: Path param, query param, standard request and response
//!     app.get(
//!         "/org/:org_id/user/:user_id",
//!         |(path, query, _headers): (Params<OrgParams>, QueryParam<OrgQueryParams>, Headers), res| async move {
//!             res.ok().json(serde_json::json!({
//!                 "org_id": path.org_id,
//!                 "user_id": path.user_id,
//!                 "query": query.query,
//!             }))
//!         },
//!     );
//!
//!     app.listen(3000, || {
//!         println!("Ripress extractor demo listening on http://localhost:3000");
//!     })
//!     .await;
//! }
//! ```
//!

/// The main application struct and its methods for configuring and running your server.
///
/// The `App` struct is the core of Ripress, providing methods to define routes, add middleware,
/// and start the HTTP server. It follows an Express.js-like pattern for route handling.
///
/// # Examples
///
/// Basic server setup:
/// ```rust
/// use ripress::{app::App, types::RouterFns, req::HttpRequest};
///
/// #[tokio::main]
/// async fn main() {
///     let mut app = App::new();
///     app.get("/", |_req: HttpRequest, res| async move { res.ok().text("Hello, World!") } );
/// }
/// ```
///
/// With middleware:
/// ```rust
/// use ripress::{app::App, types::RouterFns, req::HttpRequest};
///
/// #[tokio::main]
/// async fn main() {
///     let mut app = App::new();
///
///     app.use_cors(None)
///         .get("/api/data", |_req: HttpRequest, res| async move {
///             res.ok().json(serde_json::json!({"status": "ok"}))
///         });
/// }
/// ```
pub mod app;

/// The HTTP request struct and its methods for extracting data from requests.
///
/// `HttpRequest` provides comprehensive access to incoming HTTP request data including
/// headers, cookies, query parameters, route parameters, and request body content.
///
/// # Examples
///
/// Accessing request data:
/// ```rust
/// use ripress::context::HttpRequest;
///
/// async fn handler(req: HttpRequest, res: ripress::context::HttpResponse) -> ripress::context::HttpResponse {
///     // Get query parameters
///     let name = req.query.get("name").unwrap_or("World");
///     
///     // Get route parameters
///     let user_id = req.params.get("id");
///     
///     // Parse JSON body
///     if let Ok(data) = req.json::<serde_json::Value>() {
///         println!("Received JSON: {:?}", data);
///     }
///     
///     res.ok().text(format!("Hello, {}!", name))
/// }
/// ```
///
/// See [`req::HttpRequest`] for details.
pub mod req;

/// The HTTP response struct and its methods for building responses.
///
/// `HttpResponse` provides methods to construct HTTP responses with different status codes,
/// headers, cookies, and various body types (JSON, text, HTML, binary).
///
/// # Examples
///
/// Creating responses:
/// ```rust
/// use ripress::context::{HttpResponse, HttpRequest};
///
/// // JSON response
/// async fn json_res(req: HttpRequest, res: HttpResponse) -> HttpResponse {
///     return res.ok().json(serde_json::json!({"message": "Success"}));
/// }
///
/// // Text response with custom status
/// async fn text_res(req: HttpRequest, res: HttpResponse) -> HttpResponse {
///     return res.status(201).text("Resource created");
/// }
///
/// // Response with cookies
/// async fn cookie_res(req: HttpRequest, res: HttpResponse) -> HttpResponse {
///     return res.ok().set_cookie("session", "abc123", None).text("Logged in");
/// }
/// ```
///
/// See [`res::HttpResponse`] for details.
pub mod res;

/// Common context types for handler functions.
///
/// Re-exports [`HttpRequest`] and [`HttpResponse`] for convenience in route handlers.
/// This module provides the most commonly used types when writing route handlers.
///
/// # Examples
///
/// ```rust
/// use ripress::context::{HttpRequest, HttpResponse};
///
/// async fn my_handler(req: HttpRequest, res: HttpResponse) -> HttpResponse {
///     res.ok().text("Hello from handler!")
/// }
/// ```
pub mod context {
    pub use super::req::HttpRequest;
    pub use super::res::HttpResponse;
}

/// Utility functions and helpers for common web tasks.
///
/// This module contains helper functions for common web development tasks such as
/// parsing multipart forms, handling query parameters, and other utilities.
pub mod helpers;

/// Built-in middleware modules for CORS, logging, file uploads, and rate limiting.
///
/// Ripress includes several built-in middleware modules to handle common web application
/// concerns. These can be easily added to your application using the `App` methods.
///
/// # Available Middleware
///
/// - **CORS**: Cross-Origin Resource Sharing configuration
/// - **Logger**: Request/response logging with customizable output (requires `logger` feature)
/// - **Compression**: Response compression (gzip, deflate) (requires `compression` feature)
/// - **Rate Limiter**: Request rate limiting and throttling
/// - **Body Limit**: Request body size limiting
/// - **Shield**: Security headers and protection
/// - **File Upload**: Multipart form data and file upload handling (requires `file-upload` feature)
///
/// # Examples
///
/// ```ignore
/// use ripress::{app::App, types::RouterFns};
///
/// #[tokio::main]
/// async fn main() {
///     let mut app = App::new();
///     
///     // Add multiple middleware
///     app.use_cors(None)                    // Enable CORS    
///         .use_logger(None)                 // Enable request logging
///         .use_compression(None)            // Enable response compression
///         .use_rate_limiter(None)           // Enable rate limiting
///         .use_shield(None);                // Add security headers
/// }
/// ```
pub mod middlewares;

/// The router struct and routing logic for organizing endpoints.
///
/// The router module provides functionality for organizing and managing routes
/// in your application. While most applications will use the `App` struct directly,
/// the router can be used for more complex routing scenarios.
pub mod router;

/// Core types, traits, and enums used throughout the framework.
///
/// This module contains the fundamental types, traits, and enums that power
/// the Ripress framework, including HTTP methods, content types, and routing traits.
///
/// # Key Types
///
/// - `HttpMethods`: Enum representing HTTP methods (GET, POST, PUT, etc.)
/// - `RouterFns`: Trait for route definition methods
/// - `ResponseContentType`: Enum for response content types
/// - `RequestBodyType`: Enum for request body types
pub mod types;

/// Internal test module for framework testing.
mod tests;

/// Error types and utilities for the Ripress framework.
///
/// This module provides structured error types, error categories, and conversion utilities
/// for handling errors throughout the framework. It includes the [`RipressError`] struct,
/// the [`RipressErrorKind`] enum for classifying errors, and conversions from lower-level
/// errors such as query parameter and route parameter parsing failures.
///
/// # Error Handling
///
/// Ripress provides comprehensive error handling with structured error types that make it
/// easy to handle different kinds of errors that can occur in web applications.
///
/// # Examples
///
/// Basic error handling:
/// ```ignore
/// use ripress::error::{RipressError, RipressErrorKind};
///
/// // Create a custom error
/// let error = RipressError::new(
///     RipressErrorKind::InvalidInput,
///     "Invalid input data".to_string()
/// );
///
/// // Handle different error types
/// match error.kind() {
///     RipressErrorKind::InvalidInput => {
///         println!("Invalid data: {}", error.message());
///     }
///     RipressErrorKind::NotFound => {
///         println!("Resource not found: {}", error.message());
///     }
///     _ => {
///         println!("Other error: {}", error.message());
///     }
/// }
/// ```
///
/// See [`error::RipressError`] and [`error::RipressErrorKind`] for details.
pub mod error;

/// Procedural and attribute macros for the Ripress framework.
///
/// This module provides custom derive, attribute, and function-like macros to enhance
/// ergonomics and reduce boilerplate in web applications using Ripress.
///
/// # Features
///
/// - Derivable traits for request extraction, response serialization, etc.
/// - Route handler attribute macros (if any are defined in the framework)
/// - Utility macros for simplifying common patterns (such as routes, guards, etc.)
///
/// See the documentation for individual macros for usage examples and detailed information.
pub mod macros;

pub mod next;
pub(crate) mod url;