silent_openapi/lib.rs
1//! # Silent OpenAPI
2//!
3//! 为Silent Web框架提供OpenAPI 3.0支持,包括自动文档生成和Swagger UI集成。
4//!
5//! ## 主要特性
6//!
7//! - 🚀 基于utoipa的高性能OpenAPI文档生成
8//! - 📖 内置Swagger UI界面
9//! - 🔧 与Silent框架深度集成
10//! - 📝 支持路由文档自动收集
11//! - 🎯 零运行时开销的编译时文档生成
12//!
13//! ## 快速开始
14//!
15//! ```ignore
16//! use silent::prelude::*;
17//! use silent_openapi::{OpenApiDoc, SwaggerUiHandler};
18//! use utoipa::OpenApi;
19//!
20//! #[derive(OpenApi)]
21//! #[openapi(
22//! paths(get_hello),
23//! components(schemas())
24//! )]
25//! struct ApiDoc;
26//!
27//! async fn get_hello(_req: Request) -> Result<Response> {
28//! Ok(Response::text("Hello, OpenAPI!"))
29//! }
30//!
31//! fn main() {
32//! let route = Route::new("")
33//! .get(get_hello)
34//! .append(SwaggerUiHandler::new("/swagger-ui", ApiDoc::openapi()));
35//!
36//! Server::new().run(route);
37//! }
38//! ```
39
40pub mod doc;
41pub use silent_openapi_macros::endpoint;
42pub mod error;
43pub mod handler;
44pub mod middleware;
45pub mod route;
46pub mod schema;
47
48// 重新导出核心类型
49pub use error::{OpenApiError, Result};
50pub use handler::SwaggerUiHandler;
51pub use middleware::SwaggerUiMiddleware;
52pub use route::{DocumentedRoute, RouteDocumentation, RouteOpenApiExt};
53pub use schema::OpenApiDoc;
54
55// 重新导出utoipa的核心类型,方便用户使用
56pub use utoipa::{
57 IntoParams, IntoResponses, ToResponse, ToSchema,
58 openapi::{self, OpenApi},
59};
60
61/// Silent OpenAPI的版本信息
62pub const VERSION: &str = env!("CARGO_PKG_VERSION");
63
64/// Swagger UI 配置选项
65#[derive(Clone)]
66pub struct SwaggerUiOptions {
67 pub try_it_out_enabled: bool,
68}
69
70impl Default for SwaggerUiOptions {
71 fn default() -> Self {
72 Self {
73 try_it_out_enabled: true,
74 }
75 }
76}
77
78/// 创建一个基础的OpenAPI文档结构
79///
80/// # 参数
81///
82/// - `title`: API标题
83/// - `version`: API版本
84/// - `description`: API描述
85///
86/// # 示例
87///
88/// ```rust
89/// use silent_openapi::create_openapi_doc;
90///
91/// let openapi = create_openapi_doc(
92/// "用户管理API",
93/// "1.0.0",
94/// "基于Silent框架的用户管理系统"
95/// );
96/// ```
97pub fn create_openapi_doc(
98 title: &str,
99 version: &str,
100 description: &str,
101) -> utoipa::openapi::OpenApi {
102 use utoipa::openapi::*;
103
104 OpenApiBuilder::new()
105 .info(
106 InfoBuilder::new()
107 .title(title)
108 .version(version)
109 .description(Some(description))
110 .build(),
111 )
112 .build()
113}
114
115#[cfg(test)]
116mod tests {
117 use super::*;
118
119 #[test]
120 fn test_version() {
121 #[allow(clippy::const_is_empty)]
122 {
123 assert!(!VERSION.is_empty());
124 }
125 }
126
127 #[test]
128 fn test_create_openapi_doc() {
129 let doc = create_openapi_doc("Test API", "1.0.0", "A test API");
130 assert_eq!(doc.info.title, "Test API");
131 assert_eq!(doc.info.version, "1.0.0");
132 assert_eq!(doc.info.description, Some("A test API".to_string()));
133 }
134}