### Basic HTTP Server in Rust Source: https://context7.com/silent-rs/silent/llms.txt Sets up a minimal HTTP server using the Silent framework that listens on the default port (0.0.0.0:8080) and responds with 'hello world' to GET requests on the root path. It initializes logging to INFO level. ```rust use silent::prelude::*; fn main() { // Initialize logging logger::fmt().with_max_level(Level::INFO).init(); // Define routes let route = Route::new("") .get(|_req: Request| async { Ok("hello world") }); // Start server on default port (0.0.0.0:8080) Server::new().run(route); } ``` -------------------------------- ### Rust Task Scheduling with Silent Server Source: https://context7.com/silent-rs/silent/llms.txt Shows how to schedule asynchronous tasks using Silent's Task scheduler. This example defines a task to be executed 10 seconds in the future, which logs a message upon execution. It's integrated into a basic Silent server setup. ```rust use silent::prelude::*; use chrono::Utc; use std::sync::Arc; async fn schedule_task(mut req: Request) -> Result { let process_time = Utc::now() + chrono::Duration::seconds(10); let task = Task::create_with_action_async( "task_001".to_string(), process_time.try_into().unwrap(), "Send notification email".to_string(), Arc::new(|| { Box::pin(async { info!("Task executed at: {:?}", Utc::now()); // Perform task (send email, process data, etc.) Ok(()) }) }), ); req.scheduler()?.lock().await.add_task(task)?; Ok(format!("Task scheduled for {}", process_time)) } fn main() { let route = Route::new("schedule").post(schedule_task); Server::new().run(route); } ``` -------------------------------- ### TLS/HTTPS Server Setup in Rust Source: https://context7.com/silent-rs/silent/llms.txt This Rust code snippet shows how to configure and run a web server with TLS encryption using the Silent framework and rustls. It loads TLS certificates and private keys, creates a TLS acceptor, and binds the server to a secure HTTPS port. ```rust use silent::prelude::*; use rustls::pki_types::{CertificateDer, PrivateKeyDer}; use std::sync::Arc; use tokio_rustls::TlsAcceptor; #[tokio::main] async fn main() -> Result<(), Box> { let certs = CertificateDer::pem_file_iter("./certs/cert.pem")? .collect::, _>>()?; let key = PrivateKeyDer::from_pem_file("./certs/key.pem")?; let config = rustls::ServerConfig::builder() .with_no_client_auth() .with_single_cert(certs, key)?; let acceptor = TlsAcceptor::from(Arc::new(config)); let listener: Listener = tokio::net::TcpListener::bind("127.0.0.1:8443") .await? .into(); let route = Route::new("").get(|_req: Request| async { Ok("Secure HTTPS connection") }); Server::new() .listen(listener.tls(acceptor)) .serve(route) .await; Ok(()) } ``` -------------------------------- ### Template Rendering with Tera in Rust Source: https://context7.com/silent-rs/silent/llms.txt Renders HTML templates dynamically using the Tera template engine. This example defines a UserData struct and passes it to an 'index.html' template. It requires the 'silent' and 'serde' crates, and a 'templates' directory with an 'index.html' file. ```rust use silent::prelude::*; use serde::Serialize; #[derive(Serialize)] struct UserData { name: String, email: String, age: u32, } async fn index(_req: Request) -> Result { let user = UserData { name: "John Doe".to_string(), email: "john@example.com".to_string(), age: 30, }; Ok(TemplateResponse::from(("index.html".to_string(), user))) } fn main() { let mut route = Route::new("") .get(index) .route(); // Set template directory with glob pattern route.set_template_dir("templates/**/*"); Server::new().run(route); } ``` -------------------------------- ### Configuration System for Type-Safe Settings in Rust Source: https://context7.com/silent-rs/silent/llms.txt Implements a type-safe configuration system for applications. This example shows how to define and inject different configuration structs (DatabaseConfig, AppConfig) into request handlers. It relies on the 'silent' framework's Configs and Configs::insert functionalities. Dependencies include 'silent'. ```rust use silent::prelude::*; #[derive(Clone)] struct DatabaseConfig { url: String, max_connections: u32, } #[derive(Clone)] struct AppConfig { debug: bool, port: u16, } async fn get_db_info(req: Request) -> Result { let db_config = req.get_config::()?; Ok(format!("Database: {}", db_config.url)) } async fn get_app_info(req: Request) -> Result { let app_config = req.get_config::()?; Ok(format!("Debug: {}, Port: {}", app_config.debug, app_config.port)) } fn main() { let mut configs = Configs::new(); configs.insert(DatabaseConfig { url: "postgres://localhost/mydb".to_string(), max_connections: 10, }); configs.insert(AppConfig { debug: true, port: 8080, }); let mut route = Route::new("") .append(Route::new("db").get(get_db_info)) .append(Route::new("app").get(get_app_info)) .route(); route.set_configs(Some(configs)); Server::new().run(route); } ``` -------------------------------- ### Custom Business Error Handling with HTTP Status Codes (Rust) Source: https://context7.com/silent-rs/silent/llms.txt Demonstrates how to define and return custom business errors with specific HTTP status codes using SilentError. It includes examples of validating user IDs and checking resource permissions, returning appropriate error messages and statuses. ```rust use silent::prelude::*; use serde::Serialize; #[derive(Serialize)] struct ErrorResponse { error: String, details: String, } async fn validate_user(Path(id): Path) -> Result { if id <= 0 { return Err(SilentError::business_error( StatusCode::BAD_REQUEST, "Invalid user ID".to_string(), )); } // Simulate user lookup if id == 999 { return Err(SilentError::business_error( StatusCode::NOT_FOUND, "User not found".to_string(), )); } Ok(format!("User ID: {}", id)) } async fn protected_resource(req: Request) -> Result { // Check authorization let has_permission = false; // from auth check if !has_permission { let error_obj = ErrorResponse { error: "Forbidden".to_string(), details: "Insufficient permissions".to_string(), }; return Err(SilentError::business_error_obj( StatusCode::FORBIDDEN, serde_json::to_value(error_obj).unwrap(), )); } Ok("Protected resource data".to_string()) } fn main() { let route = Route::new("") .append(Route::new("user/").get(validate_user)) .append(Route::new("protected").get(protected_resource)); Server::new().run(route); } ``` -------------------------------- ### Session Management with Cookies in Rust Source: https://context7.com/silent-rs/silent/llms.txt Manages user sessions using cookie-based storage. This example demonstrates incrementing a visit counter stored in the session and resetting it. It utilizes the 'silent' framework's request and session manipulation capabilities. No external dependencies beyond 'silent' are strictly required for this core functionality. ```rust use silent::prelude::*; async fn increment_counter(mut req: Request) -> Result { let sessions_mut = req.sessions_mut(); let count: i64 = req.session("counter").unwrap_or(0); let new_count = count + 1; sessions_mut.insert("counter", new_count)?; Ok(format!("Visit count: {}", new_count)) } async fn reset_counter(mut req: Request) -> Result { req.sessions_mut().remove("counter"); Ok("Counter reset".to_string()) } fn main() { let route = Route::new("") .append(Route::new("visit").get(increment_counter)) .append(Route::new("reset").get(reset_counter)); Server::new().run(route); } ``` -------------------------------- ### Server-Sent Events (SSE) Streaming in Rust Source: https://context7.com/silent-rs/silent/llms.txt Streams real-time updates to clients using Server-Sent Events. This example utilizes tokio for asynchronous operations and futures_util for stream manipulation to send user connection events and periodic updates. It requires the 'silent', 'futures-util', and 'tokio' crates. ```rust use silent::prelude::*; use futures_util::StreamExt; use tokio::sync::mpsc; use tokio_stream::wrappers::UnboundedReceiverStream; #[derive(Clone)] enum Message { UserId(String), Reply(String), } async fn user_connected(_req: Request) -> Result { let (tx, rx) = mpsc::unbounded_channel(); // Simulate sending messages tokio::spawn(async move { let user_id = uuid::Uuid::new_v4().to_string(); tx.send(Message::UserId(user_id)).ok(); let mut counter = 0; loop { tokio::time::sleep(tokio::time::Duration::from_secs(1)).await; counter += 1; if tx.send(Message::Reply(format!("Update {}", counter))).is_err() { break; } } }); let rx = UnboundedReceiverStream::new(rx); let stream = rx.map(|msg| match msg { Message::UserId(id) => { Ok(SSEEvent::default().event("user").data(id)) } Message::Reply(reply) => { Ok(SSEEvent::default().data(reply)) } }); sse_reply(stream) } fn main() { let route = Route::new("events").get(user_connected); Server::new().run(route); } ``` -------------------------------- ### Static File Serving with Silent-RS Source: https://context7.com/silent-rs/silent/llms.txt This Rust code snippet demonstrates how to serve static files from a specified directory using the Silent framework. It sets up a basic route that returns a welcome message and then attaches middleware to serve files from the './static' directory. ```rust use silent::prelude::*; fn main() { let route = Route::new("") .get(|_req: Request| async { Ok("API Server") }) .with_static("static"); // Serves files from ./static directory Server::new().run(route); } // Access files at http://localhost:8080/static/style.css ``` -------------------------------- ### gRPC Service Integration with HTTP in Rust Source: https://context7.com/silent-rs/silent/llms.txt Demonstrates integrating a Tonic gRPC service with HTTP routes using the Silent framework in Rust. It defines a simple Greeter service and serves it alongside an HTTP endpoint. Dependencies include `silent` and `tonic`. ```rust use silent::prelude::*; use tonic::{Request as TonicRequest, Response, Status}; pub mod hello_world { tonic::include_proto!("hello_world"); } use hello_world::greeter_server::{Greeter, GreeterServer}; use hello_world::{HelloRequest, HelloReply}; #[derive(Debug, Default)] pub struct MyGreeter {} #[async_trait] impl Greeter for MyGreeter { async fn say_hello( &self, request: TonicRequest, ) -> std::result::Result, Status> { let name = request.into_inner().name; let reply = HelloReply { message: format!("Hello {}!", name), }; Ok(Response::new(reply)) } } #[tokio::main] async fn main() -> Result<(), Box> { let greeter = MyGreeter::default(); let greeter_server = GreeterServer::new(greeter); let route = Route::new("") .get(|_req: Request| async { Ok("HTTP endpoint") }) .append(greeter_server.service()); Server::new() .bind("0.0.0.0:50051".parse().unwrap()) .serve(route) .await; Ok(()) } ``` -------------------------------- ### Rust Custom Line Protocol Server with NetServer Source: https://context7.com/silent-rs/silent/llms.txt Demonstrates implementing a custom line-based command protocol using NetServer. The server parses incoming lines, processes commands like PING, TIME, and QUIT, and sends responses. It includes graceful shutdown. ```rust use silent::prelude::*; use std::time::Duration; use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; #[tokio::main] async fn main() -> Result<(), Box> { let handler = |stream: BoxedConnection, peer: std::net::SocketAddr| async move { info!("Client connected: {}", peer); let mut reader = BufReader::new(stream); let mut line = String::new(); loop { line.clear(); match reader.read_line(&mut line).await { Ok(0) => break, // EOF Ok(_) => { let cmd = line.trim(); let response = match cmd { "PING" => "PONG\n", "TIME" => { let now = chrono::Utc::now(); &format!("{}\n", now.to_rfc3339()) } "QUIT" => { reader.get_mut().write_all(b"BYE\n").await?; break; } _ => "UNKNOWN COMMAND\n", }; reader.get_mut().write_all(response.as_bytes()).await?; } Err(e) => { error!("Read error: {}", e); break; } } } info!("Client disconnected: {}", peer); Ok(()) }; NetServer::new() .bind("127.0.0.1:9000".parse().unwrap()) .with_shutdown(Duration::from_secs(10)) .serve(handler) .await; Ok(()) } ``` -------------------------------- ### Path Parameters with Type Validation in Rust Source: https://context7.com/silent-rs/silent/llms.txt Demonstrates how to define routes that capture path parameters with different types (String, Integer, UUID, path, and full path). The `hello_world` function extracts and returns these parameters, showcasing Silent's built-in type validation for route segments. ```rust use silent::prelude::*; use uuid::Uuid; async fn hello_world(req: Request) -> Result { let key = req.get_path_params::("key")?; Ok(format!("Hello {{}}", key)) } fn main() { let route = Route::new("path_params") // String parameter .append(Route::new("/str").get(hello_world)) // Integer parameter .append(Route::new("/int").get(hello_world)) // UUID parameter .append(Route::new("/uuid").get(hello_world)) // Path segment capture .append(Route::new("/path").get(hello_world)) // Full path capture .append(Route::new("").get(hello_world)); Server::new().run(route); } ``` -------------------------------- ### User Authentication API Source: https://context7.com/silent-rs/silent/llms.txt Handles user registration and login using password hashing with Argon2. Supports secure password storage and verification. ```APIDOC ## POST /auth/register ### Description Registers a new user by hashing their password using Argon2 and storing it. Returns a success message upon successful registration. ### Method POST ### Endpoint /auth/register ### Parameters #### Request Body - **username** (string) - Required - The username for the new account. - **password** (string) - Required - The user's chosen password. ### Request Example ```json { "username": "testuser", "password": "securepassword123" } ``` ### Response #### Success Response (200 OK) - **success** (boolean) - Indicates if the operation was successful. - **message** (string) - A message detailing the result of the operation. #### Response Example ```json { "success": true, "message": "User testuser registered" } ``` ## POST /auth/login ### Description Authenticates a user by verifying their provided password against the stored hash using Argon2. Returns a success message on valid credentials or an unauthorized error. ### Method POST ### Endpoint /auth/login ### Parameters #### Request Body - **username** (string) - Required - The user's username. - **password** (string) - Required - The user's password for verification. ### Request Example ```json { "username": "testuser", "password": "securepassword123" } ``` ### Response #### Success Response (200 OK) - **success** (boolean) - Indicates if the login was successful. - **message** (string) - A message indicating successful login. #### Error Response (401 Unauthorized) - **success** (boolean) - Indicates that the login failed. - **message** (string) - An error message indicating invalid credentials. #### Response Example ```json { "success": true, "message": "Login successful" } ``` ``` -------------------------------- ### Static File Serving API Source: https://context7.com/silent-rs/silent/llms.txt Configures the server to serve static files from a specified directory, making assets like CSS, JavaScript, and images accessible via HTTP. ```APIDOC ## GET / ### Description This endpoint serves static files from the `./static` directory. For example, `style.css` would be accessible at `/static/style.css`. ### Method GET ### Endpoint / ### Parameters None for the root endpoint, but path parameters are used for specific file requests within the static directory. ### Request Example Accessing a file like `http://localhost:8080/static/style.css`. ### Response #### Success Response (200 OK) Serves the requested static file. #### Response Example (Content of the requested static file, e.g., CSS, JS, HTML) ``` -------------------------------- ### Password Hashing with Argon2 in Rust Source: https://context7.com/silent-rs/silent/llms.txt Demonstrates how to hash and verify passwords using the Argon2 algorithm in Rust with the Silent framework. It includes request/response structures for user registration and login, handling password hashing and verification, and setting up basic routes. ```rust use silent::prelude::*; use serde::{Deserialize, Serialize}; #[derive(Deserialize)] struct RegisterRequest { username: String, password: String, } #[derive(Deserialize)] struct LoginRequest { username: String, password: String, } #[derive(Serialize)] struct AuthResponse { success: bool, message: String, } async fn register(Json(req): Json) -> Result> { // Hash password using Argon2 let password_hash = argon2::make_password(req.password)?; // Store user with hashed password (database operation omitted) // db.insert_user(&req.username, &password_hash).await?; Ok(Json(AuthResponse { success: true, message: format!("User {} registered", req.username), })) } async fn login(Json(req): Json) -> Result> { // Retrieve stored hash (database operation omitted) let stored_hash = "stored_password_hash".to_string(); // from db // Verify password using Argon2 let is_valid = argon2::verify_password(stored_hash, req.password)?; if is_valid { Ok(Json(AuthResponse { success: true, message: "Login successful".to_string(), })) } else { Err(SilentError::business_error( StatusCode::UNAUTHORIZED, "Invalid credentials".to_string(), )) } } fn main() { let route = Route::new("auth") .append(Route::new("register").post(register)) .append(Route::new("login").post(login)); Server::new().run(route); } ``` -------------------------------- ### Implement WebSocket Handler with Connection Lifecycle in Rust Source: https://context7.com/silent-rs/silent/llms.txt Creates WebSocket endpoints with robust connection lifecycle management using the Silent framework. It handles client connections, messages sent by the server, received messages, and disconnections. Dependencies include `silent::prelude::*`, `async_channel::Sender`, and `async_lock::RwLock`. ```rust use silent::prelude::*; use async_channel::Sender as ChanSender; use async_lock::RwLock; use std::sync::Arc; fn main() { let route = Route::new("ws").ws( None, WebSocketHandler::new() .on_connect( |parts: Arc>, tx: ChanSender| async move { info!("Client connected"); tx.send(Message::Text("Welcome!".to_string())).await.ok(); Ok(()) }, ) .on_send( |msg: Message, _parts: Arc>| async move { info!("Sending: {:?}", msg); Ok(msg) } ) .on_receive( |msg: Message, parts: Arc>| async move { info!("Received: {:?}", msg); // Echo back if let Message::Text(text) = msg { parts.write().await.send(Message::Text(text)).await.ok(); } Ok(()) } ) .on_close(|_parts: Arc>| async move { info!("Client disconnected"); }), ); Server::new().run(route); } ``` -------------------------------- ### WebSocket Chat Application using Rust Source: https://context7.com/silent-rs/silent/llms.txt Implements a full-featured chat room using Rust and the Silent framework. It handles user connections, disconnections, and message broadcasting. Dependencies include `silent`, `async-channel`, `async-lock`, `dashmap`, and `uuid`. ```rust use silent::prelude::*; use async_channel::Sender as ChanSender; use async_lock::RwLock; use dashmap::DashMap; use std::sync::Arc; type Users = Arc>>; #[derive(Clone)] struct ChatState { users: Users, } fn main() { let state = ChatState { users: Arc::new(DashMap::new()), }; let route = Route::new("ws").ws( None, WebSocketHandler::new() .on_connect( move |parts: Arc>, tx: ChanSender| { let users = state.users.clone(); async move { let user_id = uuid::Uuid::new_v4().to_string(); users.insert(user_id.clone(), tx.clone()); // Broadcast join notification for entry in users.iter() { if *entry.key() != user_id { let _ = entry.value() .send(Message::Text(format!("{} joined", user_id))) .await; } } parts.write().await.insert(user_id.clone()); Ok(()) } }, ) .on_receive( move |msg: Message, parts: Arc>| { let users = state.users.clone(); async move { let parts_read = parts.read().await; let user_id = parts_read.get::().unwrap(); // Broadcast message to all users if let Message::Text(text) = msg { for entry in users.iter() { let _ = entry.value() .send(Message::Text( format!("{}: {}", user_id, text) )) .await; } } Ok(()) } } ) .on_close(move |parts: Arc>| { let users = state.users.clone(); async move { let parts_read = parts.read().await; let user_id = parts_read.get::().unwrap(); users.remove(user_id); // Broadcast leave notification for entry in users.iter() { let _ = entry.value() .send(Message::Text(format!("{} left", user_id))) .await; } } }), ); Server::new().run(route); } ``` -------------------------------- ### Rate Limiting with Token Bucket in Rust Source: https://context7.com/silent-rs/silent/llms.txt Illustrates how to implement rate limiting for API requests using a token bucket algorithm in Rust with the Silent framework. It configures the rate limiter with capacity, refill rate, and maximum wait time, applying it to the server. ```rust use silent::prelude::*; use std::time::Duration; fn main() { let rate_limiter_config = RateLimiterConfig { capacity: 10, // 10 tokens refill_every: Duration::from_millis(100), // Refill every 100ms max_wait: Duration::from_secs(2), // Max wait 2 seconds }; let route = Route::new("") .get(|_req: Request| async { Ok("Rate limited endpoint") }); Server::new() .bind("127.0.0.1:8080".parse().unwrap()) .with_rate_limiter(rate_limiter_config) .run(route); } ``` -------------------------------- ### Rate Limiting Configuration Source: https://context7.com/silent-rs/silent/llms.txt Implements rate limiting for incoming requests using a token bucket algorithm to prevent abuse and manage server load. ```APIDOC ## Rate Limiting Configuration ### Description Configures the server to limit the rate of incoming requests using a token bucket algorithm. This is done during server initialization. ### Method Server Initialization Configuration ### Endpoint N/A (Applies globally to the server) ### Parameters - **capacity** (integer) - Required - The maximum number of tokens the bucket can hold (e.g., 10 requests). - **refill_every** (Duration) - Required - The interval at which tokens are added back to the bucket (e.g., 100ms). - **max_wait** (Duration) - Required - The maximum time a request will wait for a token before being rejected (e.g., 2 seconds). ### Configuration Example ```rust let rate_limiter_config = RateLimiterConfig { capacity: 10, refill_every: Duration::from_millis(100), max_wait: Duration::from_secs(2), }; Server::new() .bind("127.0.0.1:8080".parse().unwrap()) .with_rate_limiter(rate_limiter_config) .run(route); ``` ### Response Requests exceeding the rate limit will be rejected or queued based on the `max_wait` configuration. ``` -------------------------------- ### Rust TCP Echo Server with NetServer Source: https://context7.com/silent-rs/silent/llms.txt Implements a basic TCP echo server using NetServer. It binds to multiple addresses, includes rate limiting, and supports graceful shutdown. The handler echoes back any data received from clients. ```rust use silent::prelude::*; use std::time::Duration; use tokio::io::{AsyncReadExt, AsyncWriteExt}; #[tokio::main] async fn main() -> Result<(), Box> { let rate_limiter_config = RateLimiterConfig { capacity: 10, refill_every: Duration::from_millis(100), max_wait: Duration::from_secs(2), }; // TCP Echo server handler let handler = |mut stream: BoxedConnection, peer: std::net::SocketAddr| async move { info!("Connection from: {}", peer); let mut buf = vec![0u8; 1024]; loop { match stream.read(&mut buf).await { Ok(0) => break, // Connection closed Ok(n) => { // Echo back stream.write_all(&buf[..n]).await?; } Err(e) => { error!("Read error: {}", e); break; } } } Ok(()) }; NetServer::new() .bind("127.0.0.1:18080".parse().unwrap()) .bind("127.0.0.1:18081".parse().unwrap()) // Multiple bindings .with_rate_limiter(rate_limiter_config) .with_shutdown(Duration::from_secs(5)) .on_listen(|addrs| { info!("NetServer listening on: {:?}", addrs); }) .serve(handler) .await; Ok(()) } ``` -------------------------------- ### Graceful Server Shutdown Configuration (Rust) Source: https://context7.com/silent-rs/silent/llms.txt Illustrates how to configure a Silent Rust server for graceful shutdown with a specified timeout and a custom callback function. The callback can be used for cleanup operations like closing database connections or flushing logs before the server terminates. ```rust use silent::prelude::*; use std::time::Duration; #[tokio::main] async fn main() -> Result<(), Box> { let route = Route::new("") .get(|_req: Request| async { Ok("Server running") }); Server::new() .bind("127.0.0.1:8080".parse().unwrap()) .with_shutdown(Duration::from_secs(30)) // 30 second grace period .set_shutdown_callback(|| { info!("Server shutting down..."); // Cleanup: close database connections, flush logs, etc. info!("Cleanup completed"); }) .on_listen(|addrs| { info!("Server ready on: {:?}", addrs); }) .serve(route) .await; Ok(()) } ``` -------------------------------- ### Rust REST API CRUD Operations with Silent Source: https://context7.com/silent-rs/silent/llms.txt This Rust code implements a full CRUD REST API for managing users. It defines a `User` struct, uses `DashMap` for in-memory storage, and sets up routes for listing, creating, retrieving, updating, and deleting users. It relies on the `silent` framework, `serde` for serialization, and `dashmap` for concurrent data structures. ```rust use silent::prelude::*; use serde::{Deserialize, Serialize}; use std::sync::Arc; use dashmap::DashMap; #[derive(Clone, Serialize, Deserialize)] struct User { id: i64, name: String, email: String, } type UserStore = Arc>; #[derive(Clone)] struct AppState { users: UserStore, } // GET /users - List all users async fn list_users(req: Request) -> Result>> { let state = req.get_config::()?; let users: Vec = state.users.iter() .map(|entry| entry.value().clone()) .collect(); Ok(Json(users)) } // GET /users/:id - Get single user async fn get_user(req: Request) -> Result> { let id = req.get_path_params::("id")?; let state = req.get_config::()?; match state.users.get(&id) { Some(user) => Ok(Json(user.clone())), None => Err(SilentError::business_error( StatusCode::NOT_FOUND, "User not found".to_string(), )), } } // POST /users - Create user async fn create_user(req: Request, Json(mut user): Json) -> Result> { let state = req.get_config::()?; let new_id = state.users.len() as i64 + 1; user.id = new_id; state.users.insert(new_id, user.clone()); Ok(Json(user)) } // PUT /users/:id - Update user async fn update_user( req: Request, Json(updated): Json ) -> Result> { let id = req.get_path_params::("id")?; let state = req.get_config::()?; match state.users.get_mut(&id) { Some(mut user) => { user.name = updated.name; user.email = updated.email; Ok(Json(user.clone())) } None => Err(SilentError::business_error( StatusCode::NOT_FOUND, "User not found".to_string(), )), } } // DELETE /users/:id - Delete user async fn delete_user(req: Request) -> Result { let id = req.get_path_params::("id")?; let state = req.get_config::()?; match state.users.remove(&id) { Some(_) => Ok("User deleted".to_string()), None => Err(SilentError::business_error( StatusCode::NOT_FOUND, "User not found".to_string(), )), } } fn main() { let state = AppState { users: Arc::new(DashMap::new()), }; let mut route = Route::new("api/users") .get(list_users) .post(create_user) .append( Route::new("") .get(get_user) .put(update_user) .delete(delete_user) ) .route(); let mut configs = Configs::new(); configs.insert(state); route.set_configs(Some(configs)); Server::new().run(route); } ``` -------------------------------- ### TLS/HTTPS Server Configuration Source: https://context7.com/silent-rs/silent/llms.txt Enables the server to run with TLS encryption, ensuring secure HTTPS connections for clients. ```APIDOC ## TLS/HTTPS Server Setup ### Description Configures and runs the server using TLS/HTTPS to provide secure encrypted connections. Requires certificate and key files. ### Method Server Initialization Configuration ### Endpoint N/A (Applies globally to the server) ### Parameters - **certificate file** (path) - Required - Path to the TLS certificate file (e.g., `./certs/cert.pem`). - **private key file** (path) - Required - Path to the TLS private key file (e.g., `./certs/key.pem`). - **bind address** (string) - Required - The address and port to listen on (e.g., `127.0.0.1:8443`). ### Configuration Example ```rust let certs = CertificateDer::pem_file_iter("./certs/cert.pem")?.collect::, _>>()?; let key = PrivateKeyDer::from_pem_file("./certs/key.pem")?; let config = rustls::ServerConfig::builder() .with_no_client_auth() .with_single_cert(certs, key)?; let acceptor = TlsAcceptor::from(Arc::new(config)); let listener: Listener = tokio::net::TcpListener::bind("127.0.0.1:8443") .await?; Server::new() .listen(listener.tls(acceptor)) .serve(route) .await; ``` ### Response #### Success Response (200 OK) Establishes a secure HTTPS connection on the configured port. #### Response Example (A response from the server over HTTPS, e.g., `Secure HTTPS connection`) ``` -------------------------------- ### Configure CORS for API Endpoints in Rust Source: https://context7.com/silent-rs/silent/llms.txt Sets up Cross-Origin Resource Sharing for API endpoints using the Silent framework. It configures allowed origins, methods, headers, credentials, and max age for CORS requests. Dependencies include `silent::prelude::*` and `silent::middlewares::*`. ```rust use silent::prelude::*; use silent::middlewares::{Cors, CorsType}; async fn handler(_req: Request) -> Result { Ok("API response".to_string()) } fn main() { let route = Route::new("api") .hook( Cors::new() .origin(CorsType::Any) .methods(CorsType::Any) .headers(CorsType::Any) .credentials(true) .max_age(3600), ) .get(handler) .post(handler); Server::new().run(route); } ``` -------------------------------- ### Binding Server to Multiple Listeners (Rust) Source: https://context7.com/silent-rs/silent/llms.txt Shows how to configure a Silent Rust server to listen on multiple network addresses simultaneously, including standard TCP ports and Unix domain sockets. This allows the server to be accessible via different interfaces or protocols. ```rust use silent::prelude::*; #[tokio::main] async fn main() -> Result<(), Box> { let route = Route::new("") .get(|_req: Request| async { Ok("Multi-listener server") }); let server = Server::new() .bind("127.0.0.1:8080".parse().unwrap()) .bind("127.0.0.1:8081".parse().unwrap()) .bind("0.0.0.0:8082".parse().unwrap()); // Unix socket binding (non-Windows) #[cfg(not(target_os = "windows"))] let server = server.bind_unix("/tmp/silent.sock"); server.serve(route).await; Ok(()) } ``` -------------------------------- ### Handle Form Data Submissions (URL-encoded & Multipart) in Rust Source: https://context7.com/silent-rs/silent/llms.txt Parses URL-encoded and multipart form submissions, including file uploads, using the Silent framework. It demonstrates deserializing form data into a struct and handling uploaded files. Dependencies include `silent::prelude::*` and `serde::{Deserialize, Serialize}`. ```rust use silent::prelude::*; use serde::{Deserialize, Serialize}; #[derive(Deserialize, Serialize, Debug)] struct Input { name: String, email: String, } // URL-encoded form async fn accept_form(mut req: Request) -> Result> { let input: Input = req.form_parse().await?; Ok(Json(input)) } // Multipart form with file upload async fn upload_files(mut req: Request) -> Result>> { let mut filenames = vec![]; if let Some(files) = req.files("files").await { for file in files { let name = file.name().unwrap_or("file").to_string(); let path = file.path().to_string_lossy().to_string(); filenames.push(format!("{}: {}", name, path)); } } Ok(Json(filenames)) } fn main() { let route = Route::new("") .append(Route::new("submit").post(accept_form)) .append(Route::new("upload").post(upload_files)); Server::new().run(route); } ``` -------------------------------- ### User Management API Source: https://context7.com/silent-rs/silent/llms.txt This API provides full CRUD (Create, Read, Update, Delete) operations for managing user resources. It includes endpoints for listing all users, retrieving a specific user by ID, creating a new user, updating an existing user, and deleting a user. ```APIDOC ## GET /users ### Description Retrieves a list of all users. ### Method GET ### Endpoint /api/users ### Parameters #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **users** (array) - A list of user objects. - **id** (integer) - The unique identifier for the user. - **name** (string) - The name of the user. - **email** (string) - The email address of the user. #### Response Example ```json [ { "id": 1, "name": "John Doe", "email": "john.doe@example.com" }, { "id": 2, "name": "Jane Smith", "email": "jane.smith@example.com" } ] ``` ## GET /users/:id ### Description Retrieves a specific user by their unique ID. ### Method GET ### Endpoint /api/users/{id} ### Parameters #### Path Parameters - **id** (integer) - Required - The unique identifier of the user to retrieve. #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **id** (integer) - The unique identifier for the user. - **name** (string) - The name of the user. - **email** (string) - The email address of the user. #### Response Example ```json { "id": 1, "name": "John Doe", "email": "john.doe@example.com" } ``` #### Error Response (404) - **message** (string) - "User not found" ## POST /users ### Description Creates a new user. ### Method POST ### Endpoint /api/users ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **name** (string) - Required - The name of the new user. - **email** (string) - Required - The email address of the new user. ### Request Example ```json { "name": "New User", "email": "new.user@example.com" } ``` ### Response #### Success Response (200) - **id** (integer) - The unique identifier for the newly created user. - **name** (string) - The name of the new user. - **email** (string) - The email address of the new user. #### Response Example ```json { "id": 3, "name": "New User", "email": "new.user@example.com" } ``` ## PUT /users/:id ### Description Updates an existing user identified by their ID. ### Method PUT ### Endpoint /api/users/{id} ### Parameters #### Path Parameters - **id** (integer) - Required - The unique identifier of the user to update. #### Query Parameters None #### Request Body - **name** (string) - Required - The updated name of the user. - **email** (string) - Required - The updated email address of the user. ### Request Example ```json { "name": "Updated Name", "email": "updated.email@example.com" } ``` ### Response #### Success Response (200) - **id** (integer) - The unique identifier for the updated user. - **name** (string) - The updated name of the user. - **email** (string) - The updated email address of the user. #### Response Example ```json { "id": 1, "name": "Updated Name", "email": "updated.email@example.com" } ``` #### Error Response (404) - **message** (string) - "User not found" ## DELETE /users/:id ### Description Deletes a user identified by their unique ID. ### Method DELETE ### Endpoint /api/users/{id} ### Parameters #### Path Parameters - **id** (integer) - Required - The unique identifier of the user to delete. #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **message** (string) - A confirmation message indicating the user was deleted. #### Response Example ```json "User deleted" ``` #### Error Response (404) - **message** (string) - "User not found" ``` -------------------------------- ### Type-Safe Extractors in Rust for Web APIs Source: https://context7.com/silent-rs/silent/llms.txt Illustrates using Silent's type-safe extractors to parse data from requests, including path parameters, query strings, JSON bodies, and typed headers. It defines handler functions for different extraction scenarios and combines multiple extractors in one handler. ```rust use silent::prelude::*; use silent::extractor::{Path, Query, Json, TypedHeader}; use headers::UserAgent; use serde::{Deserialize, Serialize}; #[derive(Deserialize)] struct Page { page: u32, size: u32, } #[derive(Deserialize, Serialize)] struct CreateUser { name: String, age: u32, } // Extract single path parameter async fn ex_path_id(Path(id): Path) -> Result { Ok(format!("path.id={{}}", id)) } // Extract query parameters async fn ex_query(Query(p): Query) -> Result { Ok(format!("query.page={{}}, query.size={{}}", p.page, p.size)) } // Extract JSON body async fn create_user(Json(input): Json) -> Result> { // Process user creation Ok(Json(input)) } // Combine multiple extractors async fn user_detail( (Path(id), Query(p), TypedHeader(ua)): (Path, Query, TypedHeader), ) -> Result { Ok(format!( "id={{}}, page={{}}, size={{}}, user-agent={{:?}}", id, p.page, p.size, ua )) } fn main() { let route = Route::new("api") .append(Route::new("user/").get(ex_path_id)) .append(Route::new("users").get(ex_query)) .append(Route::new("user").post(create_user)) .append(Route::new("detail/").get(user_detail)); Server::new().run(route); } ``` -------------------------------- ### Custom Middleware Implementation in Rust Source: https://context7.com/silent-rs/silent/llms.txt Shows how to create and apply custom middleware in Silent using the onion model. The `MiddleWare` struct tracks request counts, performing actions before and after the request is processed by the next handler in the chain. It adds a custom header `x-request-count` to the response. ```rust use silent::prelude::*; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; struct MiddleWare { count: AtomicUsize, } #[async_trait] impl MiddleWareHandler for MiddleWare { async fn handle(&self, req: Request, next: &Next) -> Result { // Pre-request processing let count = self.count.fetch_add(1, Ordering::SeqCst); info!("pre_request count: {{}}", count); // Call next middleware/handler let mut res = next.call(req).await?; // Post-response processing res.set_header( "x-request-count", count.to_string().parse().unwrap(), ); Ok(res) } } fn main() { let middleware = Arc::new(MiddleWare { count: AtomicUsize::new(0), }); let route = Route::new("") .hook(middleware) .get(|_req: Request| async { Ok("Hello World") }); Server::new().run(route); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.