|
| 1 | +use serde::{Deserialize, Serialize}; |
| 2 | +use silent::extractor::Path; |
| 3 | +use silent::header; |
| 4 | +use silent::prelude::*; |
| 5 | +use silent_openapi::{ |
| 6 | + endpoint, OpenApiDoc, RouteOpenApiExt, SwaggerUiHandler, SwaggerUiOptions, ToSchema, |
| 7 | +}; |
| 8 | + |
| 9 | +#[derive(Serialize, Deserialize, ToSchema)] |
| 10 | +struct User { |
| 11 | + id: u64, |
| 12 | + name: String, |
| 13 | +} |
| 14 | + |
| 15 | +#[derive(Serialize, Deserialize, ToSchema)] |
| 16 | +struct ErrorResponse { |
| 17 | + code: String, |
| 18 | + message: String, |
| 19 | +} |
| 20 | + |
| 21 | +// 本示例将使用路由自动生成 OpenAPI,再补充安全定义 |
| 22 | +#[endpoint(summary = "获取问候", description = "返回 \"Hello, OpenAPI!\"")] |
| 23 | +async fn get_hello(_req: Request) -> Result<String> { |
| 24 | + Ok("Hello, OpenAPI!".into()) |
| 25 | +} |
| 26 | + |
| 27 | +#[endpoint(summary = "获取用户", description = "根据路径参数 id 返回用户信息")] |
| 28 | +async fn get_user(Path(id): Path<u64>) -> Result<User> { |
| 29 | + Ok(User { |
| 30 | + id, |
| 31 | + name: format!("User {}", id), |
| 32 | + }) |
| 33 | +} |
| 34 | + |
| 35 | +// 受保护端点:无 Authorization 返回 401,带特殊 token 返回 403,其它通过 |
| 36 | +#[endpoint(summary = "受保护示例", description = "演示 401/403 与成功的不同响应")] |
| 37 | +async fn get_protected(req: Request) -> Result<Response> { |
| 38 | + let auth = req |
| 39 | + .headers() |
| 40 | + .get(header::AUTHORIZATION) |
| 41 | + .and_then(|v| v.to_str().ok()) |
| 42 | + .map(|s| s.to_string()); |
| 43 | + match auth { |
| 44 | + None => { |
| 45 | + let body = ErrorResponse { |
| 46 | + code: "UNAUTHORIZED".into(), |
| 47 | + message: "missing Authorization".into(), |
| 48 | + }; |
| 49 | + Ok(Response::json(&body).with_status(StatusCode::UNAUTHORIZED)) |
| 50 | + } |
| 51 | + Some(value) if value.contains("forbidden") => { |
| 52 | + let body = ErrorResponse { |
| 53 | + code: "FORBIDDEN".into(), |
| 54 | + message: "token not allowed".into(), |
| 55 | + }; |
| 56 | + Ok(Response::json(&body).with_status(StatusCode::FORBIDDEN)) |
| 57 | + } |
| 58 | + Some(_) => Ok(Response::text("ok")), |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +#[tokio::main] |
| 63 | +async fn main() -> Result<()> { |
| 64 | + logger::fmt().init(); |
| 65 | + |
| 66 | + // 先构建业务路由 |
| 67 | + let routes = Route::new("") |
| 68 | + .get(get_hello) |
| 69 | + .append(Route::new("users").append(Route::new("<id:u64>").get(get_user))) |
| 70 | + .append(Route::new("protected").get(get_protected)); |
| 71 | + |
| 72 | + // 基于路由生成 OpenAPI,并补充 Bearer 安全定义与全局 security |
| 73 | + let openapi = routes.to_openapi("Test API", "1.0.0"); |
| 74 | + let openapi = OpenApiDoc::from_openapi(openapi) |
| 75 | + .add_bearer_auth("bearerAuth", Some("JWT Bearer token")) |
| 76 | + .set_global_security("bearerAuth", &[]) |
| 77 | + .into_openapi(); |
| 78 | + |
| 79 | + // 可选:关闭 Try it out(生产环境常用) |
| 80 | + let options = SwaggerUiOptions { |
| 81 | + try_it_out_enabled: true, |
| 82 | + }; |
| 83 | + let swagger = SwaggerUiHandler::with_options("/docs", openapi, options) |
| 84 | + .expect("Failed to create Swagger UI"); |
| 85 | + |
| 86 | + // 直接将 SwaggerUiHandler 转为可挂载的路由树并追加 |
| 87 | + let routes = Route::new("").append(swagger.into_route()).append(routes); |
| 88 | + |
| 89 | + println!("🚀 Server starting!"); |
| 90 | + println!("📖 API docs: http://localhost:8080/docs"); |
| 91 | + println!("🔗 Endpoints:"); |
| 92 | + println!(" GET /hello"); |
| 93 | + println!(" GET /users/{{id}}"); |
| 94 | + println!(" GET /protected - 401/403 示例: Authorization: Bearer <token>"); |
| 95 | + println!(" - 无头: 401; token 含 'forbidden': 403; 其他: 200"); |
| 96 | + |
| 97 | + let addr = "127.0.0.1:8080".parse().expect("Invalid address"); |
| 98 | + Server::new().bind(addr).serve(routes).await; |
| 99 | + Ok(()) |
| 100 | +} |
0 commit comments