### Web Application Setup with Summer-rs Source: https://github.com/summer-rs/summer-rs/blob/master/README.md Sets up a basic web application using Summer-rs, integrating web and SQLx plugins. This example demonstrates defining routes for a "hello world" message, a dynamic "hello {name}" route, and a route to fetch the database version. ```rust use summer::{auto_config, App}; use summer_sqlx::{ sqlx::{self, Row}, ConnectPool, SqlxPlugin }; use summer_web::{get, route}; use summer_web::{ error::Result, extractor::{Path, Component}, handler::TypeRouter, axum::response::IntoResponse, Router, WebConfigurator, WebPlugin, }; use anyhow::Context; #[auto_config(WebConfigurator)] #[tokio::main] async fn main() { App::new() .add_plugin(SqlxPlugin) .add_plugin(WebPlugin) .run() .await } #[get("/")] async fn hello_world() -> impl IntoResponse { "hello world" } #[route("/hello/{name}", method = "GET", method = "POST")] async fn hello(Path(name): Path) -> impl IntoResponse { format!("hello {name}") } #[get("/version")] async fn sqlx_request_handler(Component(pool): Component) -> Result { let version = sqlx::query("select version() as version") .fetch_one(&pool) .await .context("sqlx query failed")? .get("version"); Ok(version) } ``` -------------------------------- ### Start Webserver Source: https://github.com/summer-rs/summer-rs/blob/master/examples/web-middleware-example/README.md Run the Docker Compose file to set up dependencies and then start the Summer-RS web server. ```sh docker compose up -d cargo run ``` -------------------------------- ### TOML Configuration Example Source: https://github.com/summer-rs/summer-rs/blob/master/summer/Config.md Example of a TOML file corresponding to the `Config` struct, with settings under the `[my-plugin]` section. ```toml [my-plugin] a = 10 b = true ``` -------------------------------- ### Install Bootstrap with npm Source: https://github.com/summer-rs/summer-rs/blob/master/docs/sass/bootstrap/README.md Install the next version of Bootstrap using npm. Ensure you have Node.js and npm installed. ```bash npm install bootstrap@next ``` -------------------------------- ### Run Application Source: https://github.com/summer-rs/summer-rs/blob/master/examples/pubsub-example/README.md Execute this command to start the application after setting up the database. ```bash cargo run ``` -------------------------------- ### Component Initialization Order Example Source: https://github.com/summer-rs/summer-rs/blob/master/summer/COMPONENT_MACRO.md Components are initialized in dependency order. This example illustrates a chain of dependencies: `create_db` -> `create_repo` -> `create_service`. ```rust // 1. No dependencies - initialized first #[component] fn create_db() -> DbConnection { ... } // 2. Depends on DbConnection - initialized second #[component] fn create_repo(Component(db): Component) -> UserRepository { ... } // 3. Depends on UserRepository - initialized third #[component] fn create_service(Component(repo): Component) -> UserService { ... } ``` -------------------------------- ### App Setup with Auto-Configuration Source: https://github.com/summer-rs/summer-rs/blob/master/summer-web/README.md Utilize the `auto_config` macro to automatically register routes marked with `WebConfigurator`, simplifying app setup. ```rust #[auto_config(WebConfigurator)] #[tokio::main] async fn main() { App::new() .add_plugin(SqlxPlugin) .add_plugin(WebPlugin) .run() .await } ``` -------------------------------- ### Run Consumer Application Source: https://github.com/summer-rs/summer-rs/blob/master/examples/stream-kafka-example/README.md Execute this command to run the consumer binary. This will start consuming messages. ```sh cargo run --bin consumer ``` -------------------------------- ### Rust Consumer Example for Summer-Stream Source: https://github.com/summer-rs/summer-rs/blob/master/docs/content/blog/spring-stream-release.md A basic consumer setup for the summer-stream plugin to listen for messages on a specific topic and process them. The `StreamPlugin` must be added, and consumers defined. ```rust #[tokio::main] async fn main() { App::new() .add_plugin(StreamPlugin) .add_consumer(consumers()) .run() .await } fn consumers() -> Consumers { Consumers::new().typed_consumer(listen_topic_do_something) } #[stream_listener("topic")] async fn listen_topic_do_something(Json(payload): Json) { tracing::info!("{:#?}", payload); // do something } ``` -------------------------------- ### Start Docker Compose Source: https://github.com/summer-rs/summer-rs/blob/master/examples/pubsub-example/README.md Execute this command to start the postgres database in detached mode. ```bash docker compose up -d ``` -------------------------------- ### Basic App Setup with WebPlugin and Router Source: https://github.com/summer-rs/summer-rs/blob/master/summer-web/README.md Set up a Summer App with SqlxPlugin and WebPlugin, defining routes using a separate router function. ```rust use summer::App; use summer_web::{get, get_api}; use summer_web::{WebPlugin, WebConfigurator, Router, axum::response::IntoResponse, handler::TypeRouter}; use summer_sqlx::SqlxPlugin; #[tokio::main] async fn main() { App::new() .add_plugin(SqlxPlugin) .add_plugin(WebPlugin) .add_router(router()) .run() .await } fn router() -> Router { Router::new().typed_route(hello_word) } #[get("/")] async fn hello_word() -> impl IntoResponse { "hello word" } /// # The API summary title must use the head-1 in Markdown format. /// description /// description support multi line /// The get_api macro automatically collects the request parameters and response schema. /// @tag api_tag #[get_api("/api")] async fn hello_api() -> String { "hello api".to_string() } ``` -------------------------------- ### Web Application Example After Migration Source: https://github.com/summer-rs/summer-rs/blob/master/docs/content/blog/migrate-spring-rs-to-summer-rs.md A complete example of a web application using summer-rs, demonstrating its core components and routing after migration. This code is functional and ready to be used. ```rust use summer::{auto_config, App}; use summer_sqlx::{ sqlx::{self, Row}, ConnectPool, SqlxPlugin, }; use summer_web::{get, route}; use summer_web::{ error::Result, extractor::{Component, Path}, axum::response::IntoResponse, WebConfigurator, WebPlugin, }; use anyhow::Context; #[auto_config(WebConfigurator)] #[tokio::main] async fn main() { App::new() .add_plugin(SqlxPlugin) .add_plugin(WebPlugin) .run() .await } #[get("/")] async fn hello_world() -> impl IntoResponse { "hello world" } #[route("/hello/{name}", method = "GET", method = "POST")] async fn hello(Path(name): Path) -> impl IntoResponse { format!("hello {name}") } #[get("/version")] async fn sqlx_request_handler(Component(pool): Component) -> Result { let version = sqlx::query("select version() as version") .fetch_one(&pool) .await .context("sqlx query failed")? .get("version"); Ok(version) } ``` -------------------------------- ### Configure File Stream Connection Source: https://github.com/summer-rs/summer-rs/blob/master/summer-stream/README.zh.md Configure the connection for file-based streams. This example sets the stream to create the file if it does not exist. ```toml # 文件流配置 [stream.file] connect = { create_file = "CreateIfNotExists" } ``` -------------------------------- ### Install Bootstrap with Composer Source: https://github.com/summer-rs/summer-rs/blob/master/docs/sass/bootstrap/README.md Install Bootstrap using Composer, a dependency manager for PHP. Specify the version for compatibility. ```bash composer require twbs/bootstrap:5.0.0-beta3 ``` -------------------------------- ### Migrate Manual Plugins to #[component] Source: https://github.com/summer-rs/summer-rs/blob/master/summer/COMPONENT_MACRO.md This example shows the transformation from a manual `Plugin` implementation to using the `#[component]` macro for dependency injection and component creation. ```rust struct DbConnectionPlugin; #[async_trait] impl Plugin for DbConnectionPlugin { async fn build(&self, app: &mut AppBuilder) { let config = app.get_config::() .expect("DbConfig not found"); let db = DbConnection::new(&config); app.add_component(db); } fn name(&self) -> &str { "DbConnectionPlugin" } } // In main App::new() .add_plugin(DbConnectionPlugin) .run() .await; ``` ```rust #[component] fn create_db_connection( Config(config): Config, ) -> DbConnection { DbConnection::new(&config) } // In main App::new() .run() .await; ``` -------------------------------- ### Rust Web Application Example Source: https://github.com/summer-rs/summer-rs/blob/master/docs/content/blog/spring-rs-initial-version.md This Rust code sets up a basic web application using the summer-rs framework. It includes examples of a root endpoint and a dynamic route that accepts a name parameter. Ensure the summer and summer-web crates are added as dependencies. ```rust use summer::{route, get, App}; use summer_web::{ extractor::Path, handler::TypeRouter, response::IntoResponse, Router, WebConfigurator, WebPlugin, }; #[auto_config(WebConfigurator)] #[tokio::main] async fn main() { App::new() .add_plugin(WebPlugin) .run() .await } #[get("/")] async fn hello_world() -> impl IntoResponse { "hello world" } #[route("/hello/{name}", method = "GET", method = "POST")] async fn hello(Path(name): Path) -> impl IntoResponse { format!("hello {name}") } ``` -------------------------------- ### GET / Source: https://github.com/summer-rs/summer-rs/blob/master/summer-web/README.md A simple endpoint that returns a 'hello word' string. ```APIDOC ## GET / ### Description This endpoint serves a basic "hello word" message. ### Method GET ### Endpoint / ### Response #### Success Response (200) - **body** (string) - The message "hello word" #### Response Example ``` hello word ``` ``` -------------------------------- ### Install Bootstrap CSS with NuGet Source: https://github.com/summer-rs/summer-rs/blob/master/docs/sass/bootstrap/README.md Install the Bootstrap CSS package using the NuGet Package Manager Console. This command installs the core CSS. ```powershell Install-Package bootstrap ``` -------------------------------- ### Basic Dependency Injection Example Source: https://github.com/summer-rs/summer-rs/blob/master/docs/content/docs/getting-started/di.md Demonstrates a fundamental usage of dependency injection with summer-rs. Ensure the `summer-rs` crate is added to your `Cargo.toml`. ```rust use summer::di::component; #[component] struct ServiceA; #[component] struct ServiceB(ServiceA); fn main() { let service_b = ServiceB::new(); // ServiceA is automatically injected into ServiceB println!("ServiceB created successfully"); } ``` -------------------------------- ### SQLx Database Integration Setup Source: https://context7.com/summer-rs/summer-rs/llms.txt Sets up the Summer.rs application with the SqlxPlugin for asynchronous SQL database connectivity. Requires a SQLx configuration in app.toml. ```rust use summer::{auto_config, App}; use summer_sqlx::{sqlx::{self, Row}, ConnectPool, SqlxPlugin}; use summer_web::{get, error::Result, extractor::Component, WebConfigurator, WebPlugin}; #[auto_config(WebConfigurator)] #[tokio::main] async fn main() { App::new() .add_plugin(SqlxPlugin) .add_plugin(WebPlugin) .run() .await; } #[get("/users/{id}")] async fn get_user( Component(pool): Component, Path(id): Path, ) -> Result { let user = sqlx::query("SELECT name FROM users WHERE id = $1") .bind(id) .fetch_one(&pool) .await?; Ok(user.get("name")) } // Configuration: config/app.toml // [sqlx] // uri = "postgres://user:pass@localhost:5432/mydb" // max_connections = 10 // min_connections = 2 ``` -------------------------------- ### Dependency Injection with Multiple Components Source: https://github.com/summer-rs/summer-rs/blob/master/docs/content/docs/getting-started/di.md Example showcasing how to manage and inject multiple components in summer-rs. ```rust use summer::di::component; #[component] struct ComponentA; #[component] struct ComponentB; #[component] struct Container { a: ComponentA, b: ComponentB, } fn main() { let container = Container::new(); // Both ComponentA and ComponentB are injected into Container println!("Container created with components A and B"); } ``` -------------------------------- ### Install Bootstrap Sass with NuGet Source: https://github.com/summer-rs/summer-rs/blob/master/docs/sass/bootstrap/README.md Install the Bootstrap Sass package using the NuGet Package Manager Console. This command installs the Sass files for customization. ```powershell Install-Package bootstrap.sass ``` -------------------------------- ### TOML Configuration Example Source: https://github.com/summer-rs/summer-rs/blob/master/summer-job/README.md Example TOML structure for custom configuration, matching the `CustomConfig` struct defined in the Rust code. ```toml [custom] a = 1 b = true ``` -------------------------------- ### Start PostgreSQL Database Source: https://github.com/summer-rs/summer-rs/blob/master/examples/sea-orm-example/README.md Use this command to start the PostgreSQL database in detached mode using Docker Compose. ```sh docker compose up -d ``` -------------------------------- ### GET /api Source: https://github.com/summer-rs/summer-rs/blob/master/summer-web/README.md An API endpoint that returns a 'hello api' string, demonstrating the `get_api` macro. ```APIDOC ## GET /api ### Description This endpoint, marked with `#[get_api]`, returns a "hello api" string. The `get_api` macro is designed to automatically collect request parameters and response schemas. ### Method GET ### Endpoint /api ### Response #### Success Response (200) - **body** (string) - The message "hello api" #### Response Example ``` hello api ``` ``` -------------------------------- ### Summer-rs Web Plugin Initialization Source: https://github.com/summer-rs/summer-rs/blob/master/summer-web/README.md Basic setup for a Summer-rs web application with the WebPlugin. ```rust #[tokio::main] async fn main() { App::new() .add_plugin(WebPlugin) .run() .await; } ``` -------------------------------- ### gRPC Services with summer-grpc Source: https://context7.com/summer-rs/summer-rs/llms.txt This section details how to implement gRPC servers using the summer-grpc plugin with Tonic. It includes a basic greeter service example and its configuration. ```APIDOC ## gRPC Services with summer-grpc The `summer-grpc` plugin enables gRPC server implementation using Tonic. ### Request Example ```rust use summer::{auto_config, App}; use summer_grpc::{tonic, GrpcConfigurator, GrpcPlugin}; // Generated proto module mod proto { tonic::include_proto!("greeter"); } use proto::greeter_server::{Greeter, GreeterServer}; use proto::{HelloReply, HelloRequest}; #[derive(Default)] pub struct MyGreeter; #[tonic::async_trait] impl Greeter for MyGreeter { async fn say_hello( &self, request: tonic::Request, ) -> Result, tonic::Status> { let reply = HelloReply { message: format!("Hello, {}!", request.into_inner().name), }; Ok(tonic::Response::new(reply)) } } #[auto_config(GrpcConfigurator)] #[tokio::main] async fn main() { App::new() .add_service(GreeterServer::new(MyGreeter::default())) .add_plugin(GrpcPlugin) .run() .await; } ``` ### Configuration ```toml [grpc] binding = "0.0.0.0" port = 50051 graceful = true ``` ``` -------------------------------- ### Problem Details Response Format Example Source: https://github.com/summer-rs/summer-rs/blob/master/summer-web/README.md Example of the JSON structure for a Problem Details response, specifically for a validation error. ```json { "type": "https://api.myapp.com/problems/validation-error", "title": "Validation Error", "status": 400, "detail": "A basic validation error occurred" } ``` -------------------------------- ### Basic Rust Application Structure Source: https://github.com/summer-rs/summer-rs/blob/master/docs/content/docs/getting-started/quick-start.md This is a minimal example of a Rust application using summer-rs. Ensure your database is connectable before running. ```rust use summer::prelude::*; #[tokio::main] async fn main() { // Initialize the summer application let mut app = summer::app::App::new(); // Load configuration from app.toml app.config_from_file("config/app.toml").await; // Run the application app.run().await; } ``` -------------------------------- ### Job Scheduling with Summer-rs Source: https://github.com/summer-rs/summer-rs/blob/master/README.md Demonstrates setting up scheduled jobs using Summer-rs, including cron, fixed delay, and fixed rate jobs. This example integrates with SQLx to fetch the database version within a cron job. ```rust use anyhow::Context; use summer::{auto_config, App}; use summer_job::{cron, fix_delay, fix_rate}; use summer_job::{extractor::Component, JobConfigurator, JobPlugin}; use summer_sqlx::{ sqlx::{self, Row}, ConnectPool, SqlxPlugin, }; use std::time::{Duration, SystemTime}; #[auto_config(JobConfigurator)] #[tokio::main] async fn main() { App::new() .add_plugin(JobPlugin) .add_plugin(SqlxPlugin) .run() .await; tokio::time::sleep(Duration::from_secs(100)).await; } #[cron("1/10 * * * * *")] async fn cron_job(Component(db): Component) { let time: String = sqlx::query("select TO_CHAR(now(),'YYYY-MM-DD HH24:MI:SS') as time") .fetch_one(&db) .await .context("query failed") .unwrap() .get("time"); println!("cron scheduled: {:?}", time) } #[fix_delay(5)] async fn fix_delay_job() { let now = SystemTime::now(); let datetime: sqlx::types::chrono::DateTime = now.into(); let formatted_time = datetime.format("%Y-%m-%d %H:%M:%S"); println!("fix delay scheduled: {}", formatted_time) } #[fix_rate(5)] async fn fix_rate_job() { tokio::time::sleep(Duration::from_secs(10)).await; let now = SystemTime::now(); let datetime: sqlx::types::chrono::DateTime = now.into(); let formatted_time = datetime.format("%Y-%m-%d %H:%M:%S"); println!("fix rate scheduled: {}", formatted_time) } ``` -------------------------------- ### Custom Insufficient Permissions Error Example Source: https://github.com/summer-rs/summer-rs/blob/master/summer-web/README.md Example of a fully customized error response for insufficient permissions. Includes a custom problem type and instance URI. ```json { "type": "https://api.myapp.com/problems/insufficient-permissions", "title": "Insufficient Permissions", "status": 403, "detail": "You need admin privileges to perform this action", "instance": "/admin/users" } ``` -------------------------------- ### Redis Integration Setup Source: https://context7.com/summer-rs/summer-rs/llms.txt Sets up the Redis plugin for Summer.rs, providing Redis connectivity and caching capabilities via the `#[cache]` macro. Requires Redis configuration in app.toml. ```rust use summer::{auto_config, App}; use summer_redis::{cache, redis::AsyncCommands, Redis, RedisPlugin}; use summer_web::{get, post, error::Result, extractor::{Component, Path}, WebConfigurator, WebPlugin}; use summer_web::axum::response::Json; #[auto_config(WebConfigurator)] #[tokio::main] async fn main() { App::new() .add_plugin(RedisPlugin) .add_plugin(WebPlugin) .run() .await; } #[get("/get/{key}")] async fn get_value( Component(mut redis): Component, Path(key): Path, ) -> Result { let value: String = redis.get(&key).await?; Ok(value) } #[post("/set/{key}")] async fn set_value( Component(mut redis): Component, Path(key): Path, body: String, ) -> Result { redis.set(&key, &body).await?; Ok("OK".to_string()) } // Cache with TTL and conditions #[cache( "user:{id}", expire = 3600, condition = id > 0, unless = result.is_empty() )] async fn get_user_cached(id: i64) -> String { format!("User data for id: {}", id) } // Configuration: config/app.toml // [redis] // uri = "redis://127.0.0.1:6379" ``` -------------------------------- ### Generated Dependencies List Source: https://github.com/summer-rs/summer-rs/blob/master/summer/COMPONENT_MACRO.zh.md Example of the `dependencies()` method generated by the `#[component]` macro, listing detected component dependencies. ```rust fn dependencies(&self) -> Vec<&str> { vec!["__CreateDbConnectionPlugin"] } ``` -------------------------------- ### SeaORM Integration Setup Source: https://context7.com/summer-rs/summer-rs/llms.txt Integrates the SeaORM ORM with Summer.rs, enabling asynchronous database operations and pagination. Requires SeaORM configuration in app.toml. ```rust use summer::{auto_config, App}; use summer_sea_orm::{DbConn, SeaOrmPlugin, pagination::{Pagination, PaginationExt}}; use summer_web::{get, error::Result, extractor::{Component, Query, Path}, WebConfigurator, WebPlugin}; use summer_web::axum::response::Json; use sea_orm::{EntityTrait, QueryFilter, ColumnTrait}; mod entities; use entities::{prelude::User, user}; #[auto_config(WebConfigurator)] #[tokio::main] async fn main() { App::new() .add_plugin(SeaOrmPlugin) .add_plugin(WebPlugin) .run() .await; } #[derive(Deserialize)] struct UserQuery { name: Option, } #[get("/users")] async fn list_users( Component(db): Component, Query(query): Query, pagination: Pagination, ) -> Result>> { let mut select = User::find(); if let Some(name) = query.name { select = select.filter(user::Column::Name.contains(&name)); } let users = select.page(&db, &pagination).await?; Ok(Json(users)) } // Configuration: config/app.toml // [sea-orm] // uri = "postgres://user:pass@localhost:5432/mydb" // max_connections = 10 // enable_logging = true ``` -------------------------------- ### Summer-RS Application Setup with Sa-Token Source: https://github.com/summer-rs/summer-rs/blob/master/summer-sa-token/README.md Integrate SaTokenPlugin and configure it using SaTokenAuthConfigurator in your Summer-RS application's main function. ```rust use summer::{auto_config, App}; use summer_redis::RedisPlugin; use summer_sa_token::{SaTokenPlugin, SaTokenAuthConfigurator}; use summer_web::{WebPlugin, WebConfigurator}; mod config; #[auto_config(WebConfigurator)] #[tokio::main] async fn main() { App::new() .add_plugin(RedisPlugin) // Required for with-summer-redis feature .add_plugin(SaTokenPlugin) .add_plugin(WebPlugin) .sa_token_configure(config::SaTokenConfig) // Configure path-based auth .run() .await } ``` -------------------------------- ### Install Bootstrap with yarn Source: https://github.com/summer-rs/summer-rs/blob/master/docs/sass/bootstrap/README.md Add Bootstrap to your project using yarn. This is an alternative to npm for package management. ```bash yarn add bootstrap@next ``` -------------------------------- ### Configure Jobs with JobConfigurator Source: https://github.com/summer-rs/summer-rs/blob/master/summer-job/README.zh.md Implement the JobConfigurator trait to set up and add jobs to the application. This example shows basic plugin and job registration. ```rust #[tokio::main] async fn main() { App::new() .add_plugin(JobPlugin) .add_plugin(SqlxPlugin) .add_jobs(jobs()) .run() .await } fn jobs() -> Jobs { Jobs::new().typed_job(cron_job) } #[cron("1/10 * * * * *")] async fn cron_job() { println!("cron scheduled: {:?}", SystemTime::now()) } ``` -------------------------------- ### Define Custom Storage as a Service Source: https://github.com/summer-rs/summer-rs/blob/master/summer-sa-token/README.zh.md Define your custom storage as a Service using `#[derive(Service)]`. This example shows a basic structure for `MyDatabaseStorage` implementing `SaStorage`. ```rust use summer::plugin::service::Service; use summer_sa_token::SaStorage; use summer_sea_orm::DbConn; use sa_token_adapter::storage::{StorageResult, StorageError}; #[derive(Clone, Service)] pub struct MyDatabaseStorage { #[inject(component)] conn: DbConn, // 由 summer 框架自动注入 } #[async_trait] impl SaStorage for MyDatabaseStorage { async fn get(&self, key: &str) -> StorageResult> { // 你的数据库查询逻辑 todo!() } async fn set(&self, key: &str, value: &str, ttl: Option) -> StorageResult<()> { // 你的数据库插入/更新逻辑 todo!() } async fn delete(&self, key: &str) -> StorageResult<()> { // 你的数据库删除逻辑 todo!() } // ... 实现其他必需的方法 } ``` -------------------------------- ### Define User Configuration with Configurable Derive Source: https://context7.com/summer-rs/summer-rs/llms.txt Example of defining a configuration struct with the `Configurable` derive macro for type-safe configuration binding from TOML files. ```rust use serde::Deserialize; use summer::config::Configurable; use schemars::JsonSchema; #[derive(Clone, Configurable, JsonSchema, Deserialize)] #[config_prefix = "user"] struct UserConfig { username: String, project: String, #[serde(default)] star_count: i32, } // Configuration file: config/app.toml // [user] // username = "developer" // project = "my-app" // star_count = 100 ``` -------------------------------- ### Implementing Custom Storage Backend Source: https://github.com/summer-rs/summer-rs/blob/master/summer-sa-token/README.md Define a custom storage struct that implements `SaStorage` and derive `Service`. This example shows the basic structure for database integration. ```rust use summer::plugin::service::Service; use summer_sa_token::SaStorage; use summer_sea_orm::DbConn; use sa_token_adapter::storage::{StorageResult, StorageError}; #[derive(Clone, Service)] pub struct MyDatabaseStorage { #[inject(component)] conn: DbConn, // Auto-injected by summer framework } #[async_trait] impl SaStorage for MyDatabaseStorage { async fn get(&self, key: &str) -> StorageResult> { // Your database query logic todo!() } async fn set(&self, key: &str, value: &str, ttl: Option) -> StorageResult<()> { // Your database insert/update logic todo!() } async fn delete(&self, key: &str) -> StorageResult<()> { // Your database delete logic todo!() } // ... implement other required methods } ``` -------------------------------- ### Define Web Routes with summer-web Source: https://context7.com/summer-rs/summer-rs/llms.txt Demonstrates defining various HTTP routes using macros like `#[get]`, `#[post]`, and `#[routes]` within a Summer application. ```rust use summer::{auto_config, App}; use summer_web::{ axum::response::IntoResponse, error::Result, extractor::{Path, Json, Component}, get, post, route, routes, WebConfigurator, WebPlugin, }; use serde::Deserialize; #[auto_config(WebConfigurator)] #[tokio::main] async fn main() { App::new() .add_plugin(WebPlugin) .run() .await; } // Multiple routes to the same handler #[routes] #[get("/")] #[get("/hello_world")] async fn hello_world() -> impl IntoResponse { "hello world" } // Route with path parameter and multiple HTTP methods #[route("/hello/{name}", method = "GET", method = "POST")] async fn hello(Path(name): Path) -> impl IntoResponse { format!("hello {name}") } // POST endpoint with JSON body #[derive(Deserialize)] struct LoginCredentials { username: String, password: String, } #[post("/login")] async fn login(Json(credentials): Json) -> Result { if credentials.username == "admin" && credentials.password == "secret" { Ok("Login successful") } else { Ok("Login failed") } } ``` -------------------------------- ### Extract Redis Connection Manager Source: https://github.com/summer-rs/summer-rs/blob/master/summer-redis/README.zh.md Use the `Component` extractor from `summer-web` to get the registered Redis connection manager from the application state. This example demonstrates fetching all keys from Redis. ```rust async fn list_all_redis_key(Component(mut redis): Component) -> Result { let keys: Vec = redis.keys("*").await.context("redis request failed")?; Ok(Json(keys)) } ``` -------------------------------- ### Basic Validation Error Example Source: https://github.com/summer-rs/summer-rs/blob/master/summer-web/README.md Example of a basic validation error response. This is auto-generated. ```json { "type": "about:blank/basic-validation", "title": "Basic Validation Error", "status": 400, "detail": "BasicValidation occurred" } ``` -------------------------------- ### Basic Application Structure with Summer.rs Source: https://github.com/summer-rs/summer-rs/blob/master/summer/COMPONENT_MACRO.zh.md Set up a basic Summer.rs application using tokio's main macro and App::new().run(). ```rust use summer::App; #[tokio::main] async fn main() { App::new() .run() .await; } ``` -------------------------------- ### Custom Storage - Implementation Source: https://github.com/summer-rs/summer-rs/blob/master/summer-sa-token/README.md Demonstrates how to implement a custom storage backend for token management using a database. ```APIDOC ## Custom Storage - Implementation ### Description Demonstrates how to implement a custom storage backend for token management using a database. ### Step 1: Define your storage as a Service ```rust use summer::plugin::service::Service; use summer_sa_token::SaStorage; use summer_sea_orm::DbConn; use sa_token_adapter::storage::{StorageResult, StorageError}; #[derive(Clone, Service)] pub struct MyDatabaseStorage { #[inject(component)] conn: DbConn, // Auto-injected by summer framework } #[async_trait] impl SaStorage for MyDatabaseStorage { async fn get(&self, key: &str) -> StorageResult> { // Your database query logic todo!() } async fn set(&self, key: &str, value: &str, ttl: Option) -> StorageResult<()> { // Your database insert/update logic todo!() } async fn delete(&self, key: &str) -> StorageResult<()> { // Your database delete logic todo!() } // ... implement other required methods } ``` ### Step 2: Use lazy_storage in your configurator ```rust use summer::app::AppBuilder; use summer_sa_token::{lazy_storage, PathAuthBuilder, SaStorage, SaTokenConfigurator}; use std::sync::Arc; pub struct SaTokenConfig; impl SaTokenConfigurator for SaTokenConfig { fn configure_path_auth(&self, auth: PathAuthBuilder) -> PathAuthBuilder { auth.include("/api/**").exclude("/login") } fn configure_storage(&self, _app: &AppBuilder) -> Option> { // Use lazy_storage to wrap your Service-based storage // Dependencies (like DbConn) are auto-injected at runtime Some(lazy_storage::()) } } ``` ### `lazy_storage()` Function - Wraps your `#[derive(Service)]` storage with lazy component resolution. - Dependencies are automatically injected when the storage is first used. - No need to manually handle `LazyComponent` - the framework handles it internally. ``` -------------------------------- ### Implement gRPC Server with Tonic Source: https://context7.com/summer-rs/summer-rs/llms.txt Set up a gRPC server using the summer-grpc plugin and Tonic. Ensure the generated proto module is included and the service is added to the Summer App. Configuration is typically done via app.toml. ```rust use summer::{auto_config, App}; use summer_grpc::{tonic, GrpcConfigurator, GrpcPlugin}; // Generated proto module mod proto { tonic::include_proto!("greeter"); } use proto::greeter_server::{Greeter, GreeterServer}; use proto::{HelloReply, HelloRequest}; #[derive(Default)] pub struct MyGreeter; #[tonic::async_trait] impl Greeter for MyGreeter { async fn say_hello( &self, request: tonic::Request, ) -> Result, tonic::Status> { let reply = HelloReply { message: format!("Hello, {}!", request.into_inner().name), }; Ok(tonic::Response::new(reply)) } } #[auto_config(GrpcConfigurator)] #[tokio::main] async fn main() { App::new() .add_service(GreeterServer::new(MyGreeter::default())) .add_plugin(GrpcPlugin) .run() .await; } // Configuration: config/app.toml // [grpc] // binding = "0.0.0.0" // port = 50051 // graceful = true ``` -------------------------------- ### Configure PostgreSQL Connection Source: https://github.com/summer-rs/summer-rs/blob/master/summer-postgres/README.md Set up the database connection string in your configuration file under the [postgres] section. This URL specifies how to connect to your PostgreSQL instance. ```toml [postgres] connect = "postgres://root:12341234@localhost:5432/myapp_development" # Database address to connect to ``` -------------------------------- ### Circular Dependencies Example (Not Supported) Source: https://github.com/summer-rs/summer-rs/blob/master/summer/COMPONENT_MACRO.md Circular dependencies between components are not supported and will result in a panic. This example demonstrates a problematic circular dependency between `create_a` and `create_b`. ```rust // ❌ This will panic! #[component] fn create_a(Component(b): Component) -> A { ... } #[component] fn create_b(Component(a): Component) -> B { ... } ``` -------------------------------- ### Configure OpenObserve Access Token Source: https://github.com/summer-rs/summer-rs/blob/master/examples/opentelemetry-example/README.md Access OpenObserve at http://localhost:5080 and copy the access token. Set the `OTEL_EXPORTER_OTLP_HEADERS` environment variable in your `.env` file with the copied token and organization. ```sh OTEL_EXPORTER_OTLP_HEADERS="authorization=Basic ,organization=default" ``` -------------------------------- ### Configure Pub/Sub Plugin Source: https://github.com/summer-rs/summer-rs/blob/master/summer-pubsub/README.md Configure the pubsub plugin in your application's configuration file. Ensure project ID and credentials are set correctly. ```toml [pubsub] enabled = true project_id = "your-project-id" credentials = "path/to/credentials.json" endpoint = "https://pubsub.googleapis.com" ``` -------------------------------- ### GET /user/info Source: https://github.com/summer-rs/summer-rs/blob/master/summer-sa-token/README.md Access user information, automatically extracting the user ID from the authentication token. ```APIDOC ## GET /user/info ### Description This endpoint retrieves information for the currently logged-in user. The user's ID is automatically extracted from the authentication token provided in the request. ### Method GET ### Endpoint /user/info ### Parameters #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **user_id** (string) - The ID of the logged-in user. - **message** (string) - A greeting message including the user ID. #### Response Example ```json { "user_id": "current_user_id", "message": "Hello, current_user_id!" } ``` ``` -------------------------------- ### Enable OpenTelemetry Plugin Source: https://github.com/summer-rs/summer-rs/blob/master/summer-opentelemetry/README.md Configure the OpenTelemetry plugin in your application's configuration file. Set `enable` to `true` to activate the plugin at runtime. For other configurations, use environment variables as per OpenTelemetry specifications. ```toml [opentelemetry] enable = false # Whether to enable the plugin at runtime ``` -------------------------------- ### Mixing Manual Plugins and #[component] Source: https://github.com/summer-rs/summer-rs/blob/master/summer/COMPONENT_MACRO.md Demonstrates that manual `Plugin` implementations and `#[component]` macros can be used together within the same application. ```rust App::new() .add_plugin(ManualPlugin) // Manual plugin .run() .await; ``` -------------------------------- ### Web Configuration Items Source: https://github.com/summer-rs/summer-rs/blob/master/summer-web/README.md Configure web server settings, middleware, CORS, and static resource handling using TOML. ```toml [web] binding = "172.20.10.4" # IP address of the network interface to bind, default 0.0.0.0 port = 8000 # Port number to bind, default 8080 connect_info = false # Whether to use client connection information, default false graceful = true # Whether to enable graceful shutdown, default false global_prefix = "api" # Global prefix for all routes, default empty # Web middleware configuration [web.middlewares] compression = { enable = true } # Enable compression middleware catch_panic = { enable = true } # Capture panic generated by handler logger = { enable = true, level = "info" } # Enable log middleware limit_payload = { enable = true, body_limit = "5MB" } # Limit request body size timeout_request = { enable = true, timeout = 60000 } # Request timeout 60s # Cross-domain configuration cors = { enable = true, allow_origins = [ "https://summer-rs.github.io", ], allow_headers = [ "Authentication", ], allow_methods = [ "GET", "POST", ], max_age = 60 } # Static resource configuration static = { enable = true, uri = "/static", path = "static", precompressed = true, fallback = "index.html" } ``` -------------------------------- ### Circular Dependency Example (Not Supported) Source: https://github.com/summer-rs/summer-rs/blob/master/summer/COMPONENT_MACRO.zh.md Circular dependencies between components are not supported and will cause the application to panic during initialization. ```rust // ❌ 这会 panic! #[component] fn create_a(Component(b): Component) -> A { ... } #[component] fn create_b(Component(a): Component) -> B { ... } ``` -------------------------------- ### Configure Standard IO Stream Connection Source: https://github.com/summer-rs/summer-rs/blob/master/summer-stream/README.zh.md Configure the connection for standard input/output streams. Set loopback to false for typical command-line usage. ```toml # 标准流配置 [stream.stdio] connect = { loopback = false } ``` -------------------------------- ### Asynchronous Component Initialization Source: https://github.com/summer-rs/summer-rs/blob/master/summer/COMPONENT_MACRO.zh.md Demonstrates an asynchronous component creation function using the `async` keyword. This is useful for operations like database connections. ```rust #[component] async fn create_db_connection( Config(config): Config, ) -> DbConnection { let pool = sqlx::PgPool::connect(&config.url).await.unwrap(); DbConnection { pool } } ``` -------------------------------- ### Enable OpenAPI Documentation Source: https://context7.com/summer-rs/summer-rs/llms.txt Integrate OpenAPI documentation using the `openapi` feature and `#[get_api]`, `#[post_api]` macros. Define API endpoints and error types using Summer's web utilities. Configuration for the OpenAPI prefix and info is set in app.toml. ```rust use schemars::JsonSchema; use serde::Serialize; use summer::{auto_config, App}; use summer_web::{get_api, WebConfigurator, WebPlugin, ProblemDetails}; use summer_web::axum::Json; use summer_web::extractor::Path; #[auto_config(WebConfigurator)] #[tokio::main] async fn main() { App::new() .add_plugin(WebPlugin) .run() .await; } #[derive(Debug, Serialize, JsonSchema)] struct UserInfo { id: i64, name: String, } #[derive(Debug, thiserror::Error, ProblemDetails)] pub enum ApiError { #[status_code(404)] #[problem_type("https://api.example.com/errors/not-found")] #[error("User not found")] NotFound, #[status_code(400)] #[error("Invalid request")] BadRequest, } /// Get user by ID /// /// Returns user information for the given ID. /// @tag Users #[get_api("/users/{id}")] async fn get_user(Path(id): Path) -> Result, ApiError> { if id <= 0 { return Err(ApiError::BadRequest); } Ok(Json(UserInfo { id, name: "John".to_string() })) } // Configuration: config/app.toml // [web.openapi] // doc_prefix = "/docs" // info = { title = "My API", version = "1.0.0" } ``` -------------------------------- ### StpUtil API - Roles and Permissions Source: https://github.com/summer-rs/summer-rs/blob/master/summer-sa-token/README.md Allows for managing user roles and permissions, including setting, getting, and checking their existence. ```APIDOC ## StpUtil API - Roles and Permissions ### Description Allows for managing user roles and permissions, including setting, getting, and checking their existence. ### Methods - **set_roles(user_id: &str, roles: Vec)**: Sets the roles for a given user ID. - **get_roles(user_id: &str)**: Retrieves the roles for a given user ID. - **has_role(user_id: &str, role: &str)**: Checks if a user has a specific role. - **set_permissions(user_id: &str, permissions: Vec)**: Sets the permissions for a given user ID. - **get_permissions(user_id: &str)**: Retrieves the permissions for a given user ID. - **has_permission(user_id: &str, permission: &str)**: Checks if a user has a specific permission. ``` -------------------------------- ### Configure OpenTelemetry Plugin Source: https://github.com/summer-rs/summer-rs/blob/master/summer-opentelemetry/README.zh.md Configure the OpenTelemetry plugin in your application's configuration file. Set `enable` to `true` to activate the plugin at runtime. Other configurations should follow OpenTelemetry SDK standards. ```toml [opentelemetry] enable = false # 运行时是否启用该插件 ``` -------------------------------- ### Web Configuration Source: https://context7.com/summer-rs/summer-rs/llms.txt This section outlines how to configure the web server, including middleware, CORS, and compression, using TOML configuration. ```APIDOC ## Web Configuration Configure the web server with middleware, CORS, compression, and more through TOML configuration. ### Configuration Example ```toml # Example TOML configuration for web settings [web] # Enable CORS [web.cors] # origins = ["http://localhost:3000"] # Enable compression [web.compression] # enable = true # min_length = 1024 # Add custom middleware # [[web.middleware]] # name = "MyCustomMiddleware" # config = { ... } ``` ``` -------------------------------- ### Permission Management with StpUtil Source: https://github.com/summer-rs/summer-rs/blob/master/summer-sa-token/README.md Set, get, and check user permissions using StpUtil. These operations are asynchronous and may return errors. ```rust StpUtil::set_permissions("user_id", vec!["user:list".to_string()]).await?; ``` ```rust let permissions = StpUtil::get_permissions("user_id").await; ``` ```rust let has_perm = StpUtil::has_permission("user_id", "user:list").await; ``` -------------------------------- ### Configure Application Settings Source: https://github.com/summer-rs/summer-rs/blob/master/docs/content/docs/getting-started/quick-start.md Define application settings in `config/app.toml` for web port and database connection. Environment-specific files like `app-dev.toml` can override these settings. ```toml [web] port = 8000 # Configure the web service port. If not configured, the default port is 8080 [sqlx] # Configure the database connection information of sqlx uri = "mysql://user:password@127.0.0.1:3306" ``` -------------------------------- ### Role Management with StpUtil Source: https://github.com/summer-rs/summer-rs/blob/master/summer-sa-token/README.md Set, get, and check user roles using StpUtil. These operations are asynchronous and may return errors. ```rust StpUtil::set_roles("user_id", vec!["admin".to_string(), "user".to_string()]).await?; ``` ```rust let roles = StpUtil::get_roles("user_id").await; ``` ```rust let has_role = StpUtil::has_role("user_id", "admin").await; ``` -------------------------------- ### Run Auto-Reloading Development Server Source: https://github.com/summer-rs/summer-rs/blob/master/docs/content/docs/help/auto-reload.md Use cargo-watch to automatically recompile and run your Rust project when files change. Ensure cargo-watch is installed. ```sh cargo watch -x run ``` -------------------------------- ### Consume Messages with File Stream Source: https://github.com/summer-rs/summer-rs/blob/master/summer-stream/README.md Example of a consumer using the stream_listener macro to subscribe to messages from a topic. This macro simplifies message consumption. ```rust use summer_stream::StreamListener; #[stream_listener("topic")] async fn stream_listener(message: String) { println!("Received message: {}", message); } ``` -------------------------------- ### Send Messages with File Stream Source: https://github.com/summer-rs/summer-rs/blob/master/summer-stream/README.md Example of a producer using the file stream to send messages. Ensure the 'file' feature is enabled in dependencies. ```rust use summer_stream::producer::StreamProducer; use summer_stream::Streamer; #[tokio::main] async fn main() { let streamer = Streamer::new( "file://./stream", // StreamerUri "topic", // topic ) .await; let producer = streamer.create_producer().await; producer.send("hello world").await.unwrap(); producer.send("hello rust").await.unwrap(); } ``` -------------------------------- ### Basic Logger Configuration Source: https://github.com/summer-rs/summer-rs/blob/master/summer/Log-Plugin.zh.md Configure the main logger settings, including enablement, log level, format, and time style. Use `pretty_backtrace` during development for debugging. ```toml [logger] enable = true # 是否启用日志功能,默认是开启的 pretty_backtrace = false # 是否打印堆栈信息,默认是关闭的,建议只在应用开发阶段开启 level = "info" # 默认日志级别是info format = "compact" # 日志格式支持compact、pretty、json,默认是compact time_style = "system" # 日志输出所采用的时间戳,支持system、uptime、local、utc、none time_pattern = "%Y-%m-%dT%H:%M:%S" # 时间戳的输出格式,time_style为local、utc时才生效 with_fields = [ # 输出日志时携带其他字段,默认不携带以下字段 "thread_id", # 当前线程ID "thread_name", # 当前线程名 "file", # 输出该日志的源文件名字 "line_number", # 输出该日志的源文件所在行号 "internal_errors", # 当出现错误时是否输出包含的内部错误 ] override_filter = "info,axum=debug" # 重写默认的日志过滤级别,可以针对crate库指定日志级别 file = { enable = true } # 是否将日志写入文件中,默认没有开启 ``` -------------------------------- ### Compile Protobuf Interfaces Source: https://github.com/summer-rs/summer-rs/blob/master/summer-grpc/README.md Use a `build.rs` script to compile your `.proto` files into Rust code using `tonic_build::compile_protos`. ```rust fn main() -> Result<(), Box> { tonic_build::compile_protos("proto/helloworld.proto")?; Ok(()) } ``` -------------------------------- ### Automatic Job Configuration with auto_config Source: https://github.com/summer-rs/summer-rs/blob/master/summer-job/README.zh.md Use the `auto_config` procedural macro to automatically register scheduled jobs, simplifying the main function setup. ```rust #[auto_config(JobConfigurator)] #[tokio::main] async fn main() { App::new() .add_plugin(JobPlugin) .add_plugin(SqlxPlugin) .run() .await } ``` -------------------------------- ### Register a Component using #[component] Macro Source: https://github.com/summer-rs/summer-rs/blob/master/summer/COMPONENT_MACRO.zh.md Use the `#[component]` macro to automatically register a component creation function. This function can accept configuration and return the component instance. ```rust use summer::config::Config; use summer::component; #[component] fn create_db_connection( Config(config): Config, ) -> DbConnection { DbConnection { pool: sqlx::PgPool::connect(&config.url).await.unwrap(), } } ``` -------------------------------- ### Run Producer Application Source: https://github.com/summer-rs/summer-rs/blob/master/examples/stream-kafka-example/README.md Execute this command to run the producer binary. Ensure Redpanda is running. ```sh cargo run --bin producer ```