# undefined ## Guide - [Catcher](/guide/concepts/catcher.md): When a Response returns an error status code and the Body within the page is empty, Salvo will attempt to catch this error using a Catcher and display a user-friendly error page. You can obtain a system-default Catcher by calling Catcher::default(), and then add it to the Service. The default Catcher supports sending error pages in XML, JSON, HTML, and Text formats. You can add custom error-catching handlers to the Catcher by attaching hoops to this default Catcher. These error-catching handlers are still of type Handler. You can add multiple custom error-catching handlers to the Catcher via hoops. Custom error handlers can call the FlowCtrl::skip_next method after processing an error to skip subsequent error handlers and return early. - [Depot](/guide/concepts/depot.md): Depot is used to store temporary data involved in a single request. Middleware can place the temporary data it processes into the Depot for use by subsequent programs. When a server receives a request from a client browser, it creates an instance of Depot. This instance is destroyed after all middleware and Handler have finished processing the request. For example, we can set current_user in a login middleware and then read the current user information in subsequent middleware or Handler. - [Handler](/guide/concepts/handler.md) - [Concepts](/guide/concepts/index.md) - [Request](/guide/concepts/request.md): In Salvo, user request data can be obtained through Request: - [Response](/guide/concepts/response.md): In a Handler, the Response is passed as a parameter: The Response struct encapsulates all components of an HTTP response, providing a comprehensive API for constructing and manipulating HTTP responses.It supports a fluent, chainable style (e.g., res.status_code(200).body("Hello")), facilitating the smooth construction of responses.Core functionalities include:Setting status codes and headersManipulating the response body (supporting strings, bytes, files, and streaming data)Managing CookiesMultiple content rendering methodsThis struct employs a mutable reference pattern, returning a reference to itself via &mut self, allowing handlers to conveniently build and customize HTTP responses to meet various web service requirements. After the server receives a client request, any matched Handler or middleware can write data into the Response. In certain scenarios, such as when a middleware wishes to prevent the execution of subsequent middleware and Handlers, you can use FlowCtrl: - [Router](/guide/concepts/router.md) - [Writer](/guide/concepts/writer.md): Writer is used to write content into Response: Compared to Handler: The main differences between them are: Different purposes: Writer represents writing specific content into Response, implemented by concrete content such as strings, error messages, etc. In contrast, Handler is used to process the entire request.Writer is created within a Handler and consumes itself when the write function is called, making it a one-time call. On the other hand, Handler is shared across all requests.Writer can be returned as the content in the Result of a Handler.Writer does not include a FlowCtrl parameter, so it cannot control the execution flow of the entire request. Scribe implements Writer but offers fewer capabilities compared to Writer: The rendering function of Scribe only writes data into Response and cannot retrieve information from Request or Depot during this process. - [Ecosystem](/guide/ecology.md): Salvo boasts a rich ecosystem, including community-maintained modules, projects built on Salvo, and a wealth of tutorial resources. These resources can help you better utilize the Salvo framework to build high-performance web applications. Additionally, this subdirectory shares some libraries that work well with Salvo. The Rust language is rapidly evolving, and its ecosystem is characterized by numerous small, focused libraries. We hope these commonly used libraries can help you quickly get started with the Rust ecosystem, becoming like a pocketful of handy tools from Doraemon. - [Rust Date and Time Library](/guide/ecology/chrono.md): Chrono aims to provide all functionality needed to do correct operations on dates and times in the proleptic Gregorian calendar: The DateTime type is timezone-aware by default, with separate timezone-naive types.Operations that may produce an invalid or ambiguous date and time return Option or MappedLocalTime.Configurable parsing and formatting with a strftime-inspired date and time formatting syntax.The Local timezone works with the current local timezone of the OS.Types and operations are implemented to be reasonably efficient.To avoid increasing the binary size, Chrono does not ship with timezone data by default. Use the companion crates Chrono-TZ or tzfile for full timezone support. - [Rust Error Handling Libraries](/guide/ecology/error.md): thiserror provides convenient derive macros for custom error types.snafu is an error handling and reporting framework with context.anyhow is a flexible error handling and reporting library. - [Rust Memory Allocator Alternatives](/guide/ecology/jemallocator.md): :::tip The default allocator may sometimes fail to release memory promptly. It is recommended to use jemallocator as a global allocator to replace the default one. ::: jemallocator is a library linked with the jemalloc memory allocator, providing the Jemalloc unit type that implements the allocator API and can be set as #[global_allocator]. tikv-jemallocator is the successor project to jemallocator. These two crates are identical except for their names. For new projects, it is recommended to use the tikv-xxx version. - [Rust HTTP Client Library](/guide/ecology/reqwest.md): Reqwest is a high-level HTTP client library that simplifies the HTTP request handling process and provides many commonly used features: Support for both asynchronous and blocking APIsHandling various types of request bodies: plain text, JSON, URL-encoded forms, multipart formsCustomizable redirect policiesHTTP proxy supportTLS encryption enabled by defaultCookie management - [Rust Serialization Framework](/guide/ecology/serde.md): Serde is a core library in the Rust ecosystem, providing an efficient and versatile framework for serialization and deserialization. Its name is derived from the combination of "Serialization" and "Deserialization." - [Affix State Shared Data in Requests](/guide/features/affix-state.md): The Affix State middleware is used to add shared data to the Depot. To use the Affix State feature, you need to enable the affix-state feature in Cargo.toml. - [Basic Authentication](/guide/features/basic-auth.md): A middleware that provides support for Basic Auth. - [Cache](/guide/features/cache.md): Middleware that provides caching functionality. The Cache middleware can cache the StatusCode, Headers, and Body of a Response. For content that has already been cached, the Cache middleware will directly send the cached content from memory to the client when processing subsequent requests. Note: This plugin does not cache Response objects whose Body is ResBody::Stream. If applied to such a Response, Cache will not process these requests, and no error will occur. - [Caching Headers](/guide/features/caching-headers.md): A middleware that provides support for configuring caching headers. Cache control is a crucial part of web performance optimization. By correctly setting caching headers, unnecessary network requests can be reduced, thereby improving application performance. Cache-Control is an HTTP response header used to specify browser caching policies. It controls who can cache responses, under what conditions, and for how long. Internally, it includes implementations of three Handlers: CachingHeaders, Modified, and ETag. CachingHeaders is a combination of the latter two. Under normal circumstances, CachingHeaders is used. Modified: Provides cache validation based on the resource's last modified time.ETag: Uses Entity Tags to offer a more precise resource validation mechanism.CachingHeaders: Combines the above two mechanisms to provide comprehensive cache control support. Example Code - [Catching Panics in Requests](/guide/features/catch-panic.md): Catch Panic is used to capture crashes that occur during request processing in the program. For specific APIs, please refer to the documentation. Note: To use CatchPanic, you need to enable the catch-panic feature in Cargo.toml:salvo = { version = "0.95.0", features = ["catch-panic"] } - [Response Compression](/guide/features/compression.md): A middleware for compressing the content of Response. Supports three compression formats: br, gzip, and deflate. The priority and configuration of each compression method can be customized as needed. - [Concurrency Limitation](/guide/features/concurrency-limiter.md): The Concurrency Limiter middleware can control the number of concurrent requests. For specific API details, please refer to the documentation. - [Cross-Origin Control](/guide/features/cors.md): CORS (Cross-Origin Resource Sharing) is a mechanism that allows browsers to make requests to cross-origin servers, thereby overcoming the restrictions imposed by the browser's same-origin policy. - [Craft Feature](/guide/features/craft.md): Craft allows developers to automatically generate handler functions and endpoints through simple annotations, while seamlessly integrating with OpenAPI documentation generation. - [CSRF Protection](/guide/features/csrf.md) - [Flash](/guide/features/flash.md): A middleware that provides Flash Message functionality. FlashStore offers data storage and retrieval operations. CookieStore stores data in Cookies, while SessionStore stores data in Session. SessionStore must be used in conjunction with the session feature. Example Code Cookie Storage Example Session Storage Example - [Force HTTPS](/guide/features/force-https.md): The force-https middleware can redirect all requests to use the HTTPS protocol. If this middleware is applied to a Router, it will only enforce protocol redirection when a route is matched. If a page does not exist, no redirection will occur. However, a more common requirement is to automatically redirect any request, even when the route fails to match and returns a 404 error. In such cases, the middleware can be added to the Service. Middleware added to the Service will always execute, regardless of whether the request is successfully matched by a route. Example Code - [HTTP/3 Support](/guide/features/hello-h3.md): Salvo provides support for HTTP/3, which can be enabled via the quinn feature. HTTP/3 is based on the QUIC protocol and offers lower latency and better performance compared to traditional HTTP/1.1 and HTTP/2, especially in unstable network environments. - [Features](/guide/features/index.md) - [JWT Authentication](/guide/features/jwt-auth.md): JWT (JSON Web Token) is an open standard (RFC 7519) for securely transmitting information between parties. It is a compact, URL-safe method of representing claims in JSON object format, commonly used for authentication and information exchange. A JWT consists of three parts: Header - Specifies the token type and the signing algorithm usedPayload - Contains claims, such as user ID, roles, expiration time, etc.Signature - Used to verify that the message was not altered during transmission Typical usage of JWT in authentication flow: After user login, the server generates a JWT tokenThe token is returned to the client and stored (typically in localStorage or cookies)In subsequent requests, the client includes this token in the Authorization headerThe server validates the token's authenticity and grants access Provides middleware for JWT Auth authentication. - [Logging Middleware](/guide/features/logging.md): Logging plays a crucial role in web applications, as it enables: Providing detailed information about the request handling process to help developers track application behaviorAssisting in troubleshooting and debugging, especially in production environmentsMonitoring application performance and resource usageRecording user access patterns and system exceptionsMeeting security auditing and compliance requirements Salvo provides a middleware with basic logging functionality. If the middleware is added directly to a Router, it will not capture 404 errors returned when no Router matches the request. It is recommended to add it to the Service instead. Example Code - [OpenTelemetry Integration](/guide/features/open-telemetry.md): OpenTelemetry is an open-source observability framework that provides a standardized approach to collecting and exporting telemetry data from applications, including traces, metrics, and logs. It helps developers monitor application performance, troubleshoot issues, and understand the behavior of distributed systems. Key Advantages of OpenTelemetry: Unified APIs and tools with no vendor lock-inSupport for multiple programming languages and backend systemsLow-overhead data collectionRobust support for distributed tracing Provides middleware with OpenTelemetry support. You can refer to the example in the official repository. - [OpenAPI Documentation Generation](/guide/features/openapi.md): OpenAPI is an open-source specification for describing RESTful API interface designs. It defines API request and response structures, parameters, return types, error codes, and other details in JSON or YAML format, making communication between client and server more explicit and standardized. OpenAPI was originally the open-source version of the Swagger specification and has now become an independent project supported by many large enterprises and developers. Using the OpenAPI specification helps development teams collaborate better, reduce communication costs, and improve development efficiency. Additionally, OpenAPI provides developers with tools for automatically generating API documentation, mock data, and test cases, facilitating development and testing work. Salvo provides OpenAPI integration (modified from utoipa). Salvo elegantly extracts relevant OpenAPI data type information automatically from Handler based on its own characteristics. Salvo also integrates several popular open-source OpenAPI interfaces such as SwaggerUI, Scalar, RapiDoc, and ReDoc. Since Rust type names can be long and not always suitable for OpenAPI usage, salvo-oapi provides the Namer type, which allows customizing rules to change type names in OpenAPI as needed. {/* add tips for intall oapi with cargo */} :::tip This is tips for install Oapi in Salvo ::: Example Code Enter http://localhost:8698/swagger-ui in your browser to see the Swagger UI page. The OpenAPI integration in Salvo is quite elegant. For the example above, compared to a normal Salvo project, we just did the following steps: Enable the oapi feature in Cargo.toml: salvo = { workspace = true, features = ["oapi"] };Replace #[handler] with #[endpoint];Use name: QueryParam to get the value of the query string. When you visit http://localhost/hello?name=chris, the name query string will be parsed. The false in QueryParam means that this parameter is optional. If you visit http://localhost/hello, it will not report an error. On the contrary, if it is QueryParam, it means that this parameter must be provided, otherwise an error will be returned.Create OpenAPI and the corresponding Router. The merge_router in OpenApi::new("test api", "0.0.1").merge_router(&router) means that this OpenAPI obtains the necessary document information by parsing a certain route and its sub-routes. Some Handlers of routes may not provide information for generating documents, and these routes will be ignored, such as Handlers defined using the #[handler] macro instead of the #[endpoint] macro. That is to say, in actual projects, for reasons such as development progress, you can choose not to generate OpenAPI documents, or partially generate OpenAPI documents. Subsequently, you can gradually increase the number of OpenAPI interfaces generated, and all you need to do is change #[handler] to #[endpoint] and modify the function signature. - [Reverse Proxy](/guide/features/proxy.md): A reverse proxy is a server architecture that receives requests from clients and forwards them to one or more backend servers. Unlike a forward proxy (which acts on behalf of clients), a reverse proxy operates on behalf of the server side. Key advantages of reverse proxies: Load Balancing: Distributes requests across multiple serversEnhanced Security: Hides real server informationContent Caching: Improves performancePath Rewriting and Forwarding: Routes requests flexibly The Salvo framework provides middleware for reverse proxy functionality. - [Rate Limiting](/guide/features/rate-limiter.md): Middleware providing rate limiting functionality. - [Request Chain ID](/guide/features/request-id.md): The Request ID middleware is highly flexible. The ID generator (IdGenerator) is used to generate IDs, and you can define your own ID generator as long as it implements the IdGenerator trait. The default generator provided is UlidGenerator. Additionally, you can control whether to overwrite an existing requestid. You can also set header_name and other configurations. For details, please refer to the documentation. Example Code - [Static Server](/guide/features/serve-static.md): Middleware that serves static files or embedded files. For detailed API, please view the documentation. - [Session](/guide/features/session.md): Middleware providing support for Session. - [File Upload Size Limiter Middleware](/guide/features/size-limiter.md): A middleware for limiting the size of uploaded files in requests. - [Server-Sent Events (SSE)](/guide/features/sse.md) - [Third-Party WebSocket Plugin](/guide/features/third-party.md) - [Timeout Middleware](/guide/features/timeout.md): Provides middleware support for timeout handling. - [Tower Middleware Compatibility](/guide/features/tower-compat.md): Salvo provides compatibility support for the Tower ecosystem through the tower-compat feature. For specific APIs, please refer to the documentation. - [Trailing Slash](/guide/features/trailing-slash.md): A middleware for automatically adding or removing trailing /. - [WebSocket](/guide/features/websocket.md): A middleware that provides support for WebSocket. - [WebTransport](/guide/features/webtransport.md): WebTransport is a network transport protocol based on HTTP/3, providing bidirectional communication capabilities between clients and servers while ensuring low latency, high throughput, and security. - [To Master This Art](/guide/index.md) - [Quick Start](/guide/quick-start.md) - [AI Skills](/guide/topics/ai-skills.md): Salvo Skills is a collection of 27 specialized AI agent skills designed for the Salvo web framework. These skills follow the Agent Skills open standard and help AI assistants understand and generate Salvo code more effectively. - [How to Deploy Applications](/guide/topics/deployment.md): A Salvo project, after compilation, becomes an executable file. For deployment, you only need to upload this executable along with its dependent static resources to the server. For Rust-based projects, there is also a very simple deployment platform: shuttle.rs. Shuttle provides support for Salvo-like projects. For details, please refer to the official documentation. - [Graceful Shutdown](/guide/topics/graceful-shutdown.md): Graceful shutdown refers to the process where, when a server is being shut down, it does not immediately terminate all connections. Instead, it first stops accepting new requests while allowing existing requests sufficient time to complete their processing before closing the service. This approach prevents requests from being abruptly interrupted, thereby improving user experience and system reliability. Salvo provides support for graceful shutdown through the handle method of the Server, which retrieves the server handle, followed by calling the stop_graceful method to implement the shutdown. After invoking this method, the server will: Stop accepting new connection requestsWait for existing requests to complete processingForcefully close any remaining connections after a specified timeout (if provided) Here is a simple example: In the example above: server.handle() retrieves the server handle, which can be used to control the server's lifecyclehandle.stop_graceful(None) initiates the graceful shutdown process, where None indicates no timeout is set, meaning the server will wait indefinitely for all requests to completeTo set a timeout, you can pass Some(Duration), after which any remaining connections will be forcefully closed This approach is particularly suitable for applications deployed in container environments or on cloud platforms, as well as for scenarios requiring hot updates to ensure that requests are not unexpectedly interrupted. - [Error Handling](/guide/topics/handle-error.md) - [Topics](/guide/topics/index.md) - [Processing Flow](/guide/topics/processing-flow.md): Service first converts the request into Salvo's Response, then enters the routing matching phase. - [Sending Files](/guide/topics/send-file.md): Salvo can send files in several ways: NamedFile Salvo provides salvo::fs::NamedFile, which can be used to efficiently send files to clients. It does not load the entire file into memory; instead, it reads and sends only the portions requested by the client based on the Range header. In practice, using Response::send_file is a simplified way to utilize NamedFile. If you need more control over file delivery, you can use NamedFileBuilder. You can create a NamedFileBuilder via NamedFile::builder: After configuring the builder, you can send the file: Serve Static Middleware for serving static files or embedded files. StaticDir provides support for serving static files from local directories. You can pass a list of multiple directories as arguments. For example: ```rust file="/codes/static-dir-list/src/main.rs" ``` ```toml file="/codes/static-dir-list/Cargo.toml" ``` Provides support for rust-embed. For example: ```rust file="/codes/static-embed-files/src/main.rs" ``` ```toml file="/codes/static-embed-files/Cargo.toml" ``` - [Writing Tests](/guide/topics/testing.md) - [Using Template Engines](/guide/topics/use-template-engine.md): Salvo does not come with any built-in template engine, as preferences for template engine styles vary from person to person. At its core, a template engine is simply: data + template = string. Therefore, as long as the final string can be rendered, any template engine can be supported. For example, support for askama: Note: For projects that are not particularly complex, we highly recommend adopting a frontend-backend separation approach. Use more flexible and ecosystem-rich UI frameworks (such as React, Vue, Svelte, etc.) to build the frontend, with Salvo serving as the backend API service. This approach leads to higher development efficiency, clearer responsibilities between frontend and backend, and better aligns with modern web application development trends. - [Using Databases](/guide/topics/working-with-database.md): Diesel Sqlx rbatis ## Others - [Sponsorship Project](/donate.md): Our meeting here is a stroke of fate. In the vast expanse of the internet, the probability of our encounter is even smaller than the chance of us being born into this world. How about supporting the project a little? Let me remember you, and let your generosity spur me forward when I feel lazy, encouraging me to keep updating the project and making it better and better. You can transfer funds directly via Alipay or WeChat, or Buy Me a Coffee ☕: