### Basic Feather App Setup and Route Source: https://github.com/bersisse/feather/blob/master/crates/feather/README.md A minimal Feather application demonstrating how to create a new app instance, define a GET route for the root path, and start the server. This example requires no async/await. ```rust use feather::{App, middleware_fn, next}; #[middleware_fn] fn hello() -> feather::Outcome { res.send_text("Hello, world!"); next!() } fn main() { let mut app = App::new(); app.get("/", hello); app.listen("127.0.0.1:5050"); } ``` -------------------------------- ### Basic Feather App Setup and Route Source: https://github.com/bersisse/feather/blob/master/README.md A minimal example demonstrating how to create a new Feather application, define a simple GET route for the root path, and start the server. It highlights Feather's synchronous approach. ```rust use feather::{App, middleware_fn, next}; #[middleware_fn] fn hello() -> feather::Outcome { res.send_text("Hello, world!"); next!() } fn main() { let mut app = App::new(); app.get("/", hello); app.listen("127.0.0.1:5050"); } ``` -------------------------------- ### Clone and Run Feather Example (Bash) Source: https://github.com/bersisse/feather/blob/master/README.md Provides instructions for cloning the Feather project repository and running an example application. This is the recommended way to get started with development, allowing you to explore the framework's features and test its functionality. ```bash # Getting started with dev git clone https://github.com/BersisSe/feather.git cd feather cargo run --example app ``` -------------------------------- ### Create a Basic Feather Application Source: https://github.com/bersisse/feather/blob/master/crates/feather/src/docs/getting-started.md This Rust code demonstrates the minimal setup for a Feather application. It initializes a new app instance and starts a server listening on a specified address. ```rust use feather::App; fn main() { let mut app = App::new(); // Routes will be added here app.listen("127.0.0.1:5050"); } ``` -------------------------------- ### Minimal Feather-Runtime Server Example in Rust Source: https://github.com/bersisse/feather/blob/master/crates/feather-runtime/README.md Demonstrates how to set up a basic web server using Feather-Runtime. It initializes the engine, starts it, and defines a handler for incoming requests to send a simple text response. This example showcases the core functionality of the runtime. ```rust use feather_runtime::runtime::engine::Engine; use feather_runtime::http::{Request, Response}; fn main() { let engine = Engine::new("127.0.0.1:5050"); engine.start(); engine.for_each(|req: &mut Request| { let mut res = Response::default(); res.send_text("Hello from Feather-Runtime!"); res }).unwrap(); } ``` -------------------------------- ### Production Feather Server Example (Rust) Source: https://github.com/bersisse/feather/blob/master/crates/feather/src/docs/server-configuration.md A complete example of setting up a production-ready Feather server. It includes reading configuration from environment variables, defining a robust `ServerConfig` for production, setting up basic logging, defining a health check route, and starting the server. ```rust use feather::{App, ServerConfig}; use std::env; use num_cpus; fn main() { // Get configuration from environment let port = env::var("PORT") .unwrap_or_default() .parse::() .unwrap_or(5050); let host = env::var("HOST") .unwrap_or_default() .unwrap_or_else(|_| "0.0.0.0".to_string()); // Create production config let config = ServerConfig { max_body_size: 10 * 1024 * 1024, // 10MB read_timeout_secs: 60, // 60 seconds workers: num_cpus::get() * 2, // 2x cores stack_size: 256 * 1024, // 256KB }; let mut app = App::with_config(config); // Setup logging #[cfg(feature = "log")] { feather::info!("Starting server on {}:{}", host, port); } // Add routes app.get("/health", middleware!(|_req, res, _ctx| { res.send_text(r#"{{\"status\":\"ok\"}}"##); next!() })); // Start server let address = format!("{}:{}", host, port); app.listen(address); } ``` -------------------------------- ### Initialize Feather App with Logging (Rust) Source: https://github.com/bersisse/feather/blob/master/README.md Demonstrates how to initialize a new Feather application with the default logger enabled. The logger is automatically initialized when an App is created, and this example shows a basic setup where an info message is logged before the application starts listening for requests. ```rust fn main() { let mut app = App::new(); info!("Feather app ready to serve requests!"); // Your app setup here app.listen("127.0.1:5050"); } ``` -------------------------------- ### Create Basic Feather Application Source: https://context7.com/bersisse/feather/llms.txt Demonstrates how to create a new Feather application instance, define basic GET and POST routes, and start the server. It uses the `App::new()` constructor and the `listen()` method. ```rust use feather::{App, middleware, next}; fn main() { let mut app = App::new(); // Define a GET route app.get("/", middleware!(|_req, res, _ctx| { res.send_text("Hello, World!"); next!() })); // Define a POST route app.post("/users", middleware!(|req, res, _ctx| { let body = String::from_utf8_lossy(&req.body); res.set_status(201); res.send_text(format!("Created user: {}", body)); next!() })); // Start the server app.listen("127.0.0.1:5050"); } ``` -------------------------------- ### Feather RESTful API Router Example in Rust Source: https://github.com/bersisse/feather/blob/master/crates/feather/src/docs/routing.md Illustrates the creation of a composable and modular RESTful API router for 'items' using Feather in Rust. It defines routes for GET, POST, and DELETE operations, including setting status codes and returning JSON or ending responses. This example requires the 'feather' crate and its 'json!' macro. ```rust use feather::Router; pub fn item_router() -> Router { let mut router = Router::new(); // GET /items router.get("/", |_req, res, _ctx| { res.finish_json(feather::json!([{ "id": 1, "name": "Item 1" }])) }); // POST /items router.post("/", |_req, res, _ctx| { res.set_status(201).finish_json(feather::json!({ "id": 2, "name": "Item 2" })) }); // DELETE /items/:id router.delete("/:id", |_req, res, _ctx| { res.set_status(204).end() }); router } // in the main function just. app.mount("/api",item_router()) ``` -------------------------------- ### Feather Middleware Macro Example Source: https://github.com/bersisse/feather/blob/master/crates/feather/src/docs/getting-started.md This Rust snippet demonstrates the usage of the `middleware!` macro in Feather to define route handlers as closures. It outlines the parameters available within the closure. ```rust middleware!(|req, res, ctx| { // Process the request // Modify the response next!() // Continue to next middleware or finish }) ``` -------------------------------- ### Define Basic Routes (GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS) in Rust Source: https://github.com/bersisse/feather/blob/master/crates/feather/src/docs/routing.md Demonstrates how to define routes for common HTTP methods (GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS) using the `App` struct in Feather. Each route is associated with a specific path and middleware function. ```rust use feather::App; let mut app = App::new(); // GET request app.get("/", middleware!(|_req, res, _ctx| { res.send_text("GET /"); next!() })); // POST request app.post("/users", middleware!(|_req, res, _ctx| { res.send_text("POST /users"); next!() })); // PUT request app.put("/users/:id", middleware!(|_req, res, _ctx| { res.send_text("PUT /users/:id"); next!() })); // DELETE request app.delete("/users/:id", middleware!(|_req, res, _ctx| { res.send_text("DELETE /users/:id"); next!() })); // PATCH request app.patch("/items/:id", middleware!(|_req, res, _ctx| { res.send_text("PATCH /items/:id"); next!() })); // HEAD request app.head("/status", middleware!(|_req, res, _ctx| { res.set_status(200); next!() })); // OPTIONS request app.options("/api/*", middleware!(|_req, res, _ctx| { res.send_text("OPTIONS allowed"); next!() })); ``` -------------------------------- ### Configure Feather Server with ServerConfig Source: https://github.com/bersisse/feather/blob/master/crates/feather/src/docs/getting-started.md Demonstrates how to configure the Feather server using the `ServerConfig` struct. This allows setting parameters such as `max_body_size`, `read_timeout_secs`, `workers`, and `stack_size`. It requires the `feather` crate. ```rust use feather::{App, ServerConfig}; let config = ServerConfig { max_body_size: 10 * 1024 * 1024, // 10MB read_timeout_secs: 60, // 60 seconds workers: 4, // 4 worker threads stack_size: 128 * 1024, // 128KB }; let mut app = App::with_config(config); ``` -------------------------------- ### Define HTTP Routes with Feather Middleware Source: https://github.com/bersisse/feather/blob/master/crates/feather/src/docs/getting-started.md This Rust code illustrates how to define routes for different HTTP methods (GET, POST, PUT, DELETE, PATCH) in a Feather application using the middleware pattern. ```rust use feather::{App, middleware, next}; fn main() { let mut app = App::new(); // GET request app.get("/", middleware!(|_req, res, _ctx| { res.send_text("Hello, World!"); next!() })); // POST request app.post("/users", middleware!(|req, res, _ctx| { // Handle POST res.set_status(201); next!() })); // Other methods app.put("/users/:id", middleware!(|_req, res, _ctx| { res.send_text("PUT request"); next!() })); app.delete("/users/:id", middleware!(|_req, res, _ctx| { res.send_text("DELETE request"); next!() })); app.patch("/items/:id", middleware!(|_req, res, _ctx| { res.send_text("PATCH request"); next!() })); app.listen("127.0.0.1:5050"); } ``` -------------------------------- ### Configure Feather Server with Convenience Methods Source: https://github.com/bersisse/feather/blob/master/crates/feather/src/docs/getting-started.md Shows an alternative way to configure the Feather server using convenience methods chained onto an `App` instance. This method achieves the same results as using `ServerConfig` directly for setting `max_body`, `read_timeout`, `workers`, and `stack_size`. It requires the `feather` crate. ```rust app.max_body(10 * 1024 * 1024); app.read_timeout(60); app.workers(4); app.stack_size(128 * 1024); ``` -------------------------------- ### Feather JWT Authentication Example Source: https://github.com/bersisse/feather/blob/master/README.md This example demonstrates Feather's built-in JWT authentication. It shows how to generate a JWT token, set up a protected route that requires authentication, and extract claims from a valid token. ```rust use feather::{App, jwt_required, middleware_fn, next}; use feather::jwt::{JwtManager, SimpleClaims}; #[middleware_fn] fn token_route() -> feather::Outcome { let token = ctx.jwt().generate_simple("user", 1)?; res.send_text(format!("Token: {}", token)); next!() } #[jwt_required] #[middleware_fn] fn protected(claims: SimpleClaims) -> feather::Outcome { res.send_text(format!("Hello, {}!", claims.sub)); next!() } fn main() { let mut app = App::new(); let manager = JwtManager::new("secretcode"); app.context().set_jwt(manager); app.get("/token", token_route); app.get("/auth", protected); app.listen("127.0.0.1:8080"); } ``` -------------------------------- ### Build JWT-Secured API Server with Feather Macros in Rust Source: https://github.com/bersisse/feather/blob/master/crates/feather/src/docs/authentication.md An example of building a complete API server in Rust using the Feather framework and its JWT macros. It showcases defining API user claims, setting up JWT management, creating public and protected endpoints, and handling token generation and validation. ```rust use feather::{App, jwt::JwtManager, jwt_required, middleware_fn, middleware, Claim}; use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Claim, Clone)] struct ApiUser { #[required] sub: String, email: String, #[exp] exp: usize, } fn main() { let mut app = App::new(); let jwt = JwtManager::new("your-secret-key".to_string()); app.context().set_jwt(jwt); // Health check (no auth) app.get("/health", middleware!(|_req, res, _ctx| { res.send_text(r#"{"status":"ok"}"#); next!() })); // Login endpoint app.post("/auth/login", middleware!(|_req, res, ctx| { let jwt = ctx.jwt(); match jwt.generate_simple("user@example.com", 24.0) { Ok(token) => res.send_text(token), Err(_) => { res.set_status(500); res.send_text("Token generation failed"); } } next!() })); // Protected endpoints using #[jwt_required] #[jwt_required] #[middleware_fn] fn get_user_data(user: ApiUser) { res.send_text(format!(r#"{{"user":"{}"}}"#, user.sub)); next!() } #[jwt_required] #[middleware_fn] fn update_user(user: ApiUser) { res.send_text(format!("Updated user: {}", user.sub)); next!() } app.get("/api/user", get_user_data); app.put("/api/user", update_user); app.listen("127.0.0.1:5050"); } ``` -------------------------------- ### Implement Wildcard Routes in Rust Source: https://github.com/bersisse/feather/blob/master/crates/feather/src/docs/routing.md Demonstrates the use of wildcard characters (`*`) in Feather routes to match any path structure. This includes matching paths starting with a specific prefix and creating catch-all routes. ```rust // Match any path starting with /api/ app.get("/api/*", middleware!(|_req, res, _ctx| { res.send_text("API route"); next!() })); // Catch-all route app.get("/*", middleware!(|_req, res, _ctx| { res.set_status(404); res.send_text("Not found"); next!() })); ``` -------------------------------- ### Feather Finalizer Methods Example Source: https://github.com/bersisse/feather/blob/master/crates/feather/src/docs/getting-started.md This Rust code illustrates the use of `Finalizer` methods in Feather (v0.8.0+), which simplify sending responses by automatically calling `end!()`. Examples include `finalize_text`, `finalize_html`, `finalize_bytes`, and `finalize_json`. ```rust // Example using finalize_text (assuming Finalizer trait is imported) // res.finalize_text("Response body"); ``` -------------------------------- ### Add Feather Dependency to Cargo.toml Source: https://github.com/bersisse/feather/blob/master/crates/feather/src/docs/getting-started.md This snippet shows how to add the Feather framework as a dependency to your Rust project by modifying the Cargo.toml file. ```toml [dependencies] feather = "0.8" ``` -------------------------------- ### Feather JWT Authentication Example Source: https://github.com/bersisse/feather/blob/master/crates/feather/README.md An example demonstrating Feather's built-in JWT authentication. It includes middleware to generate a token and a protected route that requires a valid JWT, extracting claims. ```rust use feather::{App, jwt_required, middleware_fn, next}; use feather::jwt::{JwtManager, SimpleClaims}; #[middleware_fn] fn token_route() -> feather::Outcome { let token = ctx.jwt().generate_simple("user", 1)?; res.send_text(format!("Token: {}", token)); next!() } #[jwt_required] #[middleware_fn] fn protected(claims: SimpleClaims) -> feather::Outcome { res.send_text(format!("Hello, {}!", claims.sub)); next!() } fn main() { let mut app = App::new(); let manager = JwtManager::new("secretcode"); app.context().set_jwt(manager); app.get("/token", token_route); app.get("/auth", protected); app.listen("127.0.0.1:8080"); } ``` -------------------------------- ### Feather Modularity with Routers Source: https://github.com/bersisse/feather/blob/master/crates/feather/src/docs/getting-started.md This Rust code demonstrates how to organize routes into separate modules using the `Router` type in Feather (v0.8.0+), improving code organization for larger applications. ```rust // Inside a module or separate file pub fn user_routes() -> Router { let mut router = Router::new(); router.get("/profile", handle_profile); router } // In main.rs app.mount("/api/v1", user_routes()); ``` -------------------------------- ### User Creation Endpoint Source: https://github.com/bersisse/feather/blob/master/crates/feather/src/docs/routing.md This endpoint handles the creation of new users, returning a 201 Created status on success. ```APIDOC ## POST /users ### Description Handles the creation of new users. Returns a 201 Created status code upon successful user creation. ### Method POST ### Endpoint /users ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **(Object)** - Required - User data for creation. * **username** (string) - Required - The desired username. * **email** (string) - Required - The user's email address. ### Request Example ```json { "username": "johndoe", "email": "john.doe@example.com" } ``` ### Response #### Success Response (201) * **message** (string) - A confirmation message indicating successful user creation. #### Response Example ```json { "message": "User created successfully" } ``` ``` -------------------------------- ### Accessing Feather Application Context Source: https://github.com/bersisse/feather/blob/master/crates/feather/src/docs/getting-started.md This Rust snippet shows how to retrieve the application context in Feather, which is used for managing global state across the application. ```rust let ctx = app.context(); ``` -------------------------------- ### Integrate JWT with Rate Limiting Middleware in Rust Source: https://github.com/bersisse/feather/blob/master/crates/feather/src/docs/authentication.md Demonstrates how to combine JWT authentication with rate limiting middleware in a Rust Feather application. This example shows how to extract the JWT from the Authorization header and use it to identify authenticated users for rate limiting purposes. ```rust use std::collections::HashMap; use feather::State; #[derive(Clone)] struct RateLimiter { requests: HashMap, } fn main() { let mut app = App::new(); let jwt = JwtManager::new("secret-key".to_string()); app.context().set_jwt(jwt); app.context().set_state(State::new(RateLimiter { requests: HashMap::new(), })); app.use_middleware(middleware!(|req, res, ctx| { // Check rate limit for authenticated users if let Some(auth) = req.headers.get("Authorization") { if let Ok(auth_str) = auth.to_str() { let token = auth_str.strip_prefix("Bearer ").unwrap_or(""); let jwt = ctx.jwt(); if jwt.decode::(token).is_ok() { // Authenticated request // Add rate limiting logic here } } } next!() })); } ``` -------------------------------- ### Feather State Management with Context API Source: https://github.com/bersisse/feather/blob/master/README.md This example illustrates Feather's Context API for managing application-wide state. It shows how to define a state struct, initialize it, and access and modify it within a middleware. ```rust use feather::{App, middleware_fn, next}; #[derive(Debug)] struct Counter { pub count: i32 } #[middleware_fn] fn count() -> feather::Outcome { let counter = ctx.get_state::>().unwrap(); counter.lock().count += 1; res.send_text(format!("Counted! {}", counter.count)); next!() } fn main() { let mut app = App::new(); app.context().set_state(State::new(Counter { count: 0 })); app.get("/", count); app.listen("127.0.0.1:5050"); } ``` -------------------------------- ### Rust & TOML: JWT Authentication Setup in Feather Source: https://context7.com/bersisse/feather/llms.txt Configures JWT authentication in Feather by enabling the 'jwt' feature and setting up a JwtManager with a secret key. It includes an example of a public login route to generate tokens and a protected route that requires valid JWT authentication. ```toml [dependencies] feather = { version = "0.8", features = ["jwt"] } ``` ```rust use feather::{App, middleware, next}; use feather::jwt::{JwtManager, SimpleClaims, with_jwt_auth}; fn main() { let mut app = App::new(); // Initialize JWT manager with secret key let jwt_manager = JwtManager::new("your-super-secret-key-min-32-chars!".to_string()); app.context().set_jwt(jwt_manager); // Public route - generate token app.post("/auth/login", middleware!(|req, res, ctx| { let body = String::from_utf8_lossy(&req.body); // Validate credentials (simplified) if body.contains("username") && body.contains("password") { let jwt = ctx.jwt(); match jwt.generate_simple("user123", 24) { // 24 hour TTL Ok(token) => { res.send_text(format!(r#"{{"token":"{}"}}"#, token)); } Err(_) => { res.set_status(500); res.send_text("Token generation failed"); } } } else { res.set_status(401); res.send_text("Invalid credentials"); } next!() })); // Protected route using with_jwt_auth helper app.get("/api/profile", with_jwt_auth::(|_req, res, _ctx, claims| { res.send_text(format!("Hello, {}!", claims.sub)); next!() })); // Public health check app.get("/health", middleware!(|_req, res, _ctx| { res.send_text(r#"{{"status":"ok"}}"#); next!() })); app.listen("127.0.0.1:5050"); } ``` -------------------------------- ### Group Routes with Routers and Middleware in Rust Source: https://github.com/bersisse/feather/blob/master/crates/feather/src/docs/routing.md Shows how to organize routes into groups using the `Router` struct in Feather, starting from version 0.8.0. This allows for modularity and applying middleware to specific route groups. ```rust use feather::Router; pub fn api_v1() -> Router { let mut router = Router::new(); // This middleware only runs for routes in this router router.use_middleware(|_req, _res, _ctx| { println!("API v1 access"); next!() }); router.get("/status", |_req, res, _ctx| { res.finish_json(feather::json!({ "status": "ok" })) }); router } // In your main.rs // app.mount("/api/v1", api_v1()); ``` -------------------------------- ### Feather Request Data Handling Source: https://github.com/bersisse/feather/blob/master/crates/feather/src/docs/getting-started.md This Rust code demonstrates how to access various parts of an incoming HTTP request in Feather, including headers, the request path and method, and the request body. ```rust app.post("/data", middleware!(|req, res, _ctx| { // Get headers if let Some(content_type) = req.headers.get("Content-Type") { res.send_text(format!("Content-Type: {:?}", content_type)); } // Get request path and method println!("Method: {:?}, Path: {:?}", req.method, req.uri); // Get request body (as bytes) let body = &req.body; next!() })); ``` -------------------------------- ### Feather Middleware Implementation (Struct) Source: https://github.com/bersisse/feather/blob/master/README.md This example demonstrates implementing middleware in Feather using a struct that implements the `Middleware` trait. It shows how to access application context and log information within the middleware. ```rust use feather::{middleware_fn, Request, Response, AppContext, Middleware, next, info}; struct CustomMiddleware(String); impl Middleware for CustomMiddleware { fn handle(&self, _request: &mut Request, _response: &mut Response, _ctx: &AppContext) -> feather::Outcome { info!("Hii I am a Struct Middleware and this is my data: {}", self.0); next!() } } ``` -------------------------------- ### Create Feather App with Custom ServerConfig Source: https://github.com/bersisse/feather/blob/master/crates/feather/src/docs/server-configuration.md Illustrates creating a Feather application with a custom `ServerConfig`. This allows fine-tuning parameters like `max_body_size`, `read_timeout_secs`, `workers`, and `stack_size` before starting the server. ```rust use feather::{App, ServerConfig}; fn main() { let config = ServerConfig { max_body_size: 10 * 1024 * 1024, // 10MB read_timeout_secs: 60, // 60 seconds workers: 4, // 4 worker threads stack_size: 128 * 1024, // 128KB }; let mut app = App::with_config(config); app.listen("127.0.0.1:5050"); } ``` -------------------------------- ### Feather Middleware Implementation (Function) Source: https://github.com/bersisse/feather/blob/master/README.md This example shows how to implement middleware in Feather using a function decorated with `middleware_fn`. It demonstrates adding a global middleware that logs a message before proceeding to the next handler. ```rust use feather::{App, middleware_fn, next}; #[middleware_fn] fn log_middleware() -> feather::Outcome { println!("Custom global middleware!"); next!() } #[middleware_fn] fn hello() -> feather::Outcome { res.send_text("Hello, world!"); next!() } fn main() { let mut app = App::new(); app.use_middleware(log_middleware); app.get("/", hello); app.listen("127.0.0.1:5050"); } ``` -------------------------------- ### Extract Path Parameters in Rust Source: https://github.com/bersisse/feather/blob/master/crates/feather/src/docs/routing.md Illustrates how to define routes with path parameters using the `:paramName` syntax in Feather and extract these parameters within the middleware using `req.param("paramName")`. ```rust app.get("/users/:id", middleware!(|req, res, _ctx| { // The framework captures the path structure let user = req.param("id"); // Returns a option res.send_text(format!("User ID from path {}", user.unwrap())); next!() })); app.get("/posts/:postId/comments/:commentId", middleware!(|_req, res, _ctx| { let post_id = req.param("postId") let comment_id = req.param("commentId") res.send_text("Post and comment IDs"); next!() })); ``` -------------------------------- ### Chain Middleware in Feather (Rust) Source: https://github.com/bersisse/feather/blob/master/crates/feather/src/docs/middlewares.md This example illustrates how to apply multiple middleware functions. While direct chaining isn't shown, it demonstrates using global middleware for common validations followed by route-specific middleware. ```rust // Global middleware for all routes app.use_middleware(middleware!(|req, res, _ctx| { // Validation 1 next!() })); app.use_middleware(middleware!(|req, res, _ctx| { // Validation 2 next!() })); // Route-specific middleware app.post("/users", middleware!(|req, res, _ctx| { // Route handler next!() })); ``` -------------------------------- ### Define Generic Routes with Specific HTTP Methods in Rust Source: https://github.com/bersisse/feather/blob/master/crates/feather/src/docs/routing.md Explains how to use the generic `route()` method in Feather for defining routes with specific HTTP methods, providing flexibility for advanced routing scenarios. ```rust use feather::Method; app.route(Method::GET, "/custom", middleware!(|_req, res, _ctx| { res.send_text("Custom route"); next!() })); app.route(Method::POST, "/api/data", middleware!(|_req, res, _ctx| { res.send_text("API data handler"); next!() })); ``` -------------------------------- ### Feather Middleware Function Example Source: https://github.com/bersisse/feather/blob/master/crates/feather/README.md Demonstrates defining a middleware function in Feather using the `middleware_fn` attribute. This middleware logs a message and then calls the next middleware in the chain. ```rust use feather::{middleware_fn, next}; #[middleware_fn] fn log_middleware() -> feather::Outcome { println!("Custom global middleware!"); next!() } ``` -------------------------------- ### Set Feather stack_size for Standard Usage Source: https://github.com/bersisse/feather/blob/master/crates/feather/src/docs/server-configuration.md Example of setting the default `stack_size` in Feather for standard usage. This provides a balanced approach for most applications. ```rust // Standard usage app.stack_size(64 * 1024); // 64KB (default) ``` -------------------------------- ### Access Feather Application State in Middleware (Rust) Source: https://github.com/bersisse/feather/blob/master/crates/feather/src/docs/middlewares.md This example shows how to set and access application-wide state within middleware using the `ctx` parameter. It defines a `Config` struct and retrieves its `api_key` from the context. ```rust use feather::State; #[derive(Clone)] struct Config { api_key: String, } fn main() { let mut app = App::new(); // Set state app.context().set_state(State::new(Config { api_key: "secret-key".to_string(), })); // Access state in middleware app.use_middleware(middleware!(|_req, res, ctx| { let config = ctx.get_state::>(); let api_key = config.with_scope(|c| c.api_key.clone()); res.send_text(format!("API Key: {}", api_key)); next!() })); } ``` -------------------------------- ### Set Feather stack_size for Simple Operations Source: https://github.com/bersisse/feather/blob/master/crates/feather/src/docs/server-configuration.md Example of setting a minimal `stack_size` in Feather for simple operations. This configuration uses less memory but requires careful consideration to avoid stack overflows. ```rust // For simple operations app.stack_size(32 * 1024); // 32KB (minimum safe) ``` -------------------------------- ### Rust Struct-Based Middleware Implementation Source: https://github.com/bersisse/feather/blob/master/crates/feather/src/docs/middlewares.md Provides an example of implementing the `Middleware` trait on a Rust struct for more complex middleware logic. The `handle` method within the struct implements the middleware's behavior and must return an `Outcome`. ```rust use feather::{Middleware, MiddlewareResult, Outcome, Request, Response, AppContext}; struct LoggingMiddleware; impl Middleware for LoggingMiddleware { fn handle(&self, req: &mut Request, res: &mut Response, _ctx: &AppContext) -> Outcome { println!("[{{}}] {{}}", req.method, req.uri); Ok(MiddlewareResult::Next) } } // Use it in your app app.use_middleware(LoggingMiddleware); ``` -------------------------------- ### Feather Response: Set Status Code Source: https://github.com/bersisse/feather/blob/master/crates/feather/src/docs/getting-started.md This Rust example demonstrates how to set an HTTP status code for a response in a Feather application, such as indicating successful resource creation (201). ```rust app.post("/users", middleware!(|_req, res, _ctx| { res.set_status(201); res.send_text("User created"); next!() })); ``` -------------------------------- ### Database Connection Pool Setup in Rust Source: https://github.com/bersisse/feather/blob/master/crates/feather/src/docs/state-management.md Demonstrates setting up a database connection pool using a custom `Database` struct and integrating it with Feather's state management for request handling. It shows how to query the database within a request handler. ```rust use feather::State; #[derive(Clone)] struct Database { connection_string: String, } impl Database { fn query(&self, sql: &str) -> Vec { // Execute query vec![] } } fn main() { let mut app = App::new(); let db = Database { connection_string: "postgresql://localhost/db".to_string(), }; app.context().set_state(State::new(db)); app.get("/users", middleware!(|_req, res, ctx| { let db = ctx.get_state::>(); let users = db.with_scope(|database| { database.query("SELECT * FROM users") }); res.send_text(format!("Users: {:?}", users)); next!() })); } ``` -------------------------------- ### Configuration Management Setup in Rust Source: https://github.com/bersisse/feather/blob/master/crates/feather/src/docs/state-management.md Illustrates how to set up application configuration using a `Config` struct and Feather's state management. This allows configuration values like host, port, and debug mode to be accessible throughout the application. ```rust #[derive(Clone)] struct Config { port: u16, host: String, debug: bool, } fn main() { let mut app = App::new(); app.context().set_state(State::new(Config { port: 5050, host: "127.0.0.1".to_string(), debug: true, })); } ``` -------------------------------- ### Create Feather App with Default Configuration Source: https://github.com/bersisse/feather/blob/master/crates/feather/src/docs/server-configuration.md Demonstrates how to create a new Feather application instance using the default server configuration. The app is then set to listen on a specified address and port. ```rust use feather::App; fn main() { let mut app = App::new(); // Uses default configuration app.listen("127.0.0.1:5050"); } ``` -------------------------------- ### Feather Global vs. Route-Specific Middleware Source: https://github.com/bersisse/feather/blob/master/crates/feather/src/docs/getting-started.md This Rust code differentiates between global middleware (applied to all requests) and route-specific middleware (applied only to a particular route) in Feather. ```rust // Global middleware - runs on every request app.use_middleware(middleware!(|req, res, _ctx| { println!("Request to: {}", req.uri); next!() })); // Route-specific middleware app.get("/", middleware!(|_req, res, _ctx| { res.send_text("Home page"); next!() })); ``` -------------------------------- ### Define Feather Routes with HTTP Methods Source: https://context7.com/bersisse/feather/llms.txt Illustrates how to define routes for various HTTP methods (GET, PUT, DELETE, PATCH) using the App struct's corresponding methods. It shows how to handle dynamic route parameters and wildcard routes. ```rust use feather::{App, middleware, next}; fn main() { let mut app = App::new(); // GET request app.get("/users/:id", middleware!(|req, res, _ctx| { let user_id = req.param("id").unwrap_or("unknown"); res.send_text(format!("User ID: {}", user_id)); next!() })); // PUT request app.put("/users/:id", middleware!(|req, res, _ctx| { res.send_text("User updated"); next!() })); // DELETE request app.delete("/users/:id", middleware!(|req, res, _ctx| { res.set_status(204); next!() })); // PATCH request app.patch("/items/:id", middleware!(|req, res, _ctx| { res.send_text("Item patched"); next!() })); // Wildcard route (catch-all) app.get("/api/*", middleware!(|req, res, _ctx| { res.send_text(format!("API route: {}", req.uri)); next!() })); app.listen("127.0.0.1:5050"); } ``` -------------------------------- ### Feather Response: Send Text Source: https://github.com/bersisse/feather/blob/master/crates/feather/src/docs/getting-started.md This Rust code shows how to send a plain text response to a client in a Feather application. It's typically used within a route handler. ```rust app.get("/", middleware!(|_req, res, _ctx| { res.send_text("Hello, World!"); next!() })); ``` -------------------------------- ### Listen on Different Addresses with Feather (Rust) Source: https://github.com/bersisse/feather/blob/master/crates/feather/src/docs/server-configuration.md Illustrates how to configure the Feather server to listen on various network addresses and ports using the `listen()` method. It covers examples for localhost, all interfaces, IPv6, and hostnames, demonstrating flexibility in network binding. ```rust use feather::App; let mut app = App::new(); // Listen on localhost port 5050 app.listen("127.0.0.1:5050"); // Listen on all interfaces app.listen("0.0.0.0:8080"); // Listen on IPv6 app.listen("[::1]:5050"); // Listen on all IPv6 interfaces app.listen("[::]:8080"); // Listen on hostname app.listen("localhost:5050"); // Multiple addresses with string app.listen("127.0.0.1:5050"); ``` -------------------------------- ### Configure Feather App using Convenience Methods Source: https://github.com/bersisse/feather/blob/master/crates/feather/src/docs/server-configuration.md Shows how to configure a Feather application after its creation using chained convenience methods. This approach allows setting `max_body`, `read_timeout`, `workers`, and `stack_size` dynamically. ```rust use feather::App; fn main() { let mut app = App::new(); app.max_body(10 * 1024 * 1024) // 10MB .read_timeout(60) // 60 seconds .workers(4) // 4 threads .stack_size(128 * 1024); // 128KB app.listen("127.0.0.1:5050"); } ``` -------------------------------- ### Feather Response: Send JSON (with json feature) Source: https://github.com/bersisse/feather/blob/master/crates/feather/src/docs/getting-started.md This Rust code snippet shows how to send a JSON response using the `send_json` method, provided the `json` feature is enabled for the Feather crate. It uses a macro for convenient JSON construction. ```rust #[cfg(feature = "json")] app.get("/api/data", middleware!(|_req, res, _ctx| { res.send_json(feather::json!({ "status": "ok", "data": [1, 2, 3] })); next!() })); ``` -------------------------------- ### Custom Validation Flow with `#[jwt_required]` (Rust) Source: https://github.com/bersisse/feather/blob/master/crates/feather/src/docs/authentication.md Implements a custom authorization logic within a protected route using `#[jwt_required]` and a `#[middleware_fn]`. This example checks for a specific 'admin' role in the JWT claims before allowing access. Requires a JWT with a 'role' field. ```rust #[derive(Serialize, Deserialize, Claim, Clone)] struct AdminClaims { #[required] sub: String, role: String, #[exp] exp: usize, } #[jwt_required] #[middleware_fn] fn admin_only(claims: AdminClaims) { if claims.role != "admin" { res.set_status(403); res.send_text("Admin access required"); return next!(); } res.send_text(format!("Admin panel for: {}", claims.sub)); next!() } let mut app = App::new(); app.get("/api/admin", admin_only); ``` -------------------------------- ### Metrics and Counters Setup in Rust Source: https://github.com/bersisse/feather/blob/master/crates/feather/src/docs/state-management.md Shows how to implement and manage application metrics, such as request counts and error counts, using a `Metrics` struct and Feather's state management. Metrics are recorded within middleware to track application activity. ```rust #[derive(Clone)] struct Metrics { requests: i64, errors: i64, } impl Metrics { fn record_request(&mut self) { self.requests += 1; } fn record_error(&mut self) { self.errors += 1; } } fn main() { let mut app = App::new(); app.context().set_state(State::new(Metrics { requests: 0, errors: 0, })); // Record metrics in middleware app.use_middleware(middleware!(|_req, res, ctx| { let metrics = ctx.get_state::>(); metrics.with_mut_scope(|m| { m.record_request(); }); next!() })); } ``` -------------------------------- ### Protect Feather Route with #[jwt_required] Macro (Rust) Source: https://github.com/bersisse/feather/blob/master/crates/feather/src/docs/authentication.md This example demonstrates how to protect a Feather API route using the `#[jwt_required]` and `#[middleware_fn]` macros. The macro automatically handles token extraction, decoding, validation, and returns a 401 Unauthorized error if checks fail. ```rust use feather::{App, jwt::JwtManager, jwt_required, middleware_fn, Claim}; use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Claim, Clone)] struct UserClaims { #[required] pub sub: String, pub email: String, } #[jwt_required] #[middleware_fn] fn get_profile(claims: UserClaims) { res.send_text(format!("Profile for: {}", claims.email)); next!() } fn main() { let mut app = App::new(); let jwt = JwtManager::new("secret-key".to_string()); app.context().set_jwt(jwt); // Protected route - automatically validates JWT app.get("/api/profile", get_profile); app.listen("127.0.0.1:5050"); } ``` -------------------------------- ### Handle JWT Errors Gracefully in Rust Source: https://github.com/bersisse/feather/blob/master/crates/feather/src/docs/authentication.md Provides an example of robust JWT error handling in Rust. It specifically checks for expired signatures and invalid tokens, returning appropriate HTTP status codes and messages. This ensures a better user experience when token validation fails. ```rust use feather::jwt::ErrorKind; let token = "invalid-token"; let jwt = ctx.jwt(); match jwt.decode::(token) { Ok(claims) => { // Token is valid } Err(e) => { if e.kind() == jsonwebtoken::errors::ErrorKind::ExpiredSignature { res.set_status(401); res.send_text("Token expired"); } else if e.kind() == jsonwebtoken::errors::ErrorKind::InvalidToken { res.set_status(401); res.send_text("Invalid token"); } else { res.set_status(401); res.send_text("Authentication failed"); } } } ``` -------------------------------- ### User Session Management Setup in Rust Source: https://github.com/bersisse/feather/blob/master/crates/feather/src/docs/state-management.md Demonstrates a simple user session management system using a `Sessions` struct and Feather's state management. It initializes a HashMap to store session data, keyed by session IDs. ```rust use std::collections::HashMap; use feather::State; #[derive(Clone)] struct Session { user_id: Option, } #[derive(Clone)] struct Sessions { sessions: HashMap, } fn main() { let mut app = App::new(); app.context().set_state(State::new(Sessions { sessions: HashMap::new(), })); } ``` -------------------------------- ### Feather State Management with Context API Source: https://github.com/bersisse/feather/blob/master/crates/feather/README.md Demonstrates using Feather's Context API to manage application state. A `Counter` struct is used to track request counts, demonstrating mutable state access within middleware. ```rust use feather::{App, middleware_fn, next, State}; #[derive(Debug)] struct Counter { pub count: i32 } #[middleware_fn] fn count() -> feather::Outcome { let counter = ctx.get_state::>().unwrap(); counter.lock().count += 1; res.send_text(format!("Counted! {}", counter.count)); next!() } fn main() { let mut app = App::new(); app.context().set_state(State::new(Counter { count: 0 })); app.get("/", count); app.listen("127.0.0.1:5050"); } ``` -------------------------------- ### Feather Deadlock Prevention Example in Rust Source: https://github.com/bersisse/feather/blob/master/crates/feather/src/docs/state-management.md Warns against accessing the same `State` recursively within Feather, as this can lead to deadlocks. Provides an example of incorrect recursive access and a refactored, correct approach that avoids nested locks. ```rust // DON'T DO THIS - Will cause deadlock! let state = ctx.get_state::>(); state.with_scope(|data| { let state_again = ctx.get_state::>(); // ❌ DEADLOCK! state_again.with_scope(|_| { /* ... */ }); }); // DO THIS - No deadlock let state = ctx.get_state::>(); let value = state.with_scope(|data| { // Extract what you need data.some_field.clone() }); // Now you can access again if needed let state = ctx.get_state::>(); state.with_scope(|data| { /* ... */ }); ``` -------------------------------- ### Not Found Endpoint Source: https://github.com/bersisse/feather/blob/master/crates/feather/src/docs/routing.md This endpoint simulates a resource not found scenario, returning a 404 Not Found status code. ```APIDOC ## GET /not-found ### Description This endpoint is designed to return a 404 Not Found status, indicating that the requested resource could not be found on the server. ### Method GET ### Endpoint /not-found ### Parameters None ### Request Example None ### Response #### Success Response (404) * **message** (string) - A message indicating the resource was not found. #### Response Example ```json { "message": "Resource not found" } ``` ``` -------------------------------- ### Forbidden Access Endpoint Source: https://github.com/bersisse/feather/blob/master/crates/feather/src/docs/routing.md This endpoint simulates a forbidden access scenario, returning a 403 Forbidden status code. ```APIDOC ## GET /forbidden ### Description This endpoint is designed to return a 403 Forbidden status, indicating that the client does not have permission to access the requested resource. ### Method GET ### Endpoint /forbidden ### Parameters None ### Request Example None ### Response #### Success Response (403) * **message** (string) - A message indicating access denied. #### Response Example ```json { "message": "Access denied" } ``` ``` -------------------------------- ### Rust Middleware Creation using middleware! Macro Source: https://github.com/bersisse/feather/blob/master/crates/feather/src/docs/middlewares.md Illustrates creating inline middlewares in Rust using the `middleware!` macro. This is suitable for short, localized logic where defining a separate function is unnecessary. It requires calling `next!()` to proceed. ```rust app.get("/", middleware!(|_req, res, _ctx| { res.send_text("Quick response"); next!() })); ``` -------------------------------- ### Feather Control Flow Macros: next!, next_route!, end! Source: https://context7.com/bersisse/feather/llms.txt Demonstrates the usage of `next!()` to continue processing, `next_route!()` to skip to the next matching route, and `end!()` to terminate request processing immediately within Feather middleware. This example shows conditional logic for authorization and route skipping. ```rust use feather::{App, middleware, middleware_fn, next, next_route, end, MiddlewareResult}; #[middleware_fn] fn auth_check() -> feather::Outcome { let token = req.headers.get("Authorization"); if token.is_none() { res.set_status(401); res.send_text("Unauthorized"); return end!(); // Stop processing immediately } next!() // Continue to next middleware } #[middleware_fn] fn conditional_route() -> feather::Outcome { if req.uri.contains("skip") { return next_route!(); // Skip to next matching route } res.send_text("Processed this route"); next!() } fn main() { let mut app = App::new(); // Auth middleware runs first app.use_middleware(auth_check); // Route with conditional processing app.get("/data/*", conditional_route); // Fallback route (reached if next_route! is called) app.get("/data/*", middleware!(|_req, res, _ctx| { res.send_text("Fallback handler"); next!() })); app.listen("127.0.0.1:5050"); } ```