wae_schema/swagger_ui/
mod.rs1#![warn(missing_docs)]
6
7use std::fmt::Write;
8
9#[derive(Debug, Clone)]
11pub struct SwaggerUiConfig {
12 pub openapi_url: String,
14 pub title: String,
16}
17
18impl Default for SwaggerUiConfig {
19 fn default() -> Self {
21 Self { openapi_url: "/openapi.json".to_string(), title: "Swagger UI".to_string() }
22 }
23}
24
25impl SwaggerUiConfig {
26 pub fn new() -> Self {
28 Self::default()
29 }
30
31 pub fn openapi_url(mut self, url: impl Into<String>) -> Self {
33 self.openapi_url = url.into();
34 self
35 }
36
37 pub fn title(mut self, title: impl Into<String>) -> Self {
39 self.title = title.into();
40 self
41 }
42}
43
44pub fn generate_html(config: &SwaggerUiConfig) -> String {
46 let mut html = String::new();
47 writeln!(&mut html, "<!DOCTYPE html>").unwrap();
48 writeln!(&mut html, "<html lang=\"zh-CN\">").unwrap();
49 writeln!(&mut html, "<head>").unwrap();
50 writeln!(&mut html, " <meta charset=\"UTF-8\">").unwrap();
51 writeln!(&mut html, " <title>{}</title>", config.title).unwrap();
52 writeln!(
53 &mut html,
54 " <link rel=\"stylesheet\" type=\"text/css\" href=\"https://unpkg.com/swagger-ui-dist@5/swagger-ui.css\">"
55 )
56 .unwrap();
57 writeln!(&mut html, " <style>").unwrap();
58 writeln!(&mut html, " html {{ box-sizing: border-box; overflow: -moz-scrollbars-vertical; overflow-y: scroll; }}")
59 .unwrap();
60 writeln!(&mut html, " *, *:before, *:after {{ box-sizing: inherit; }}").unwrap();
61 writeln!(&mut html, " body {{ margin: 0; background: #fafafa; }}").unwrap();
62 writeln!(&mut html, " </style>").unwrap();
63 writeln!(&mut html, "</head>").unwrap();
64 writeln!(&mut html, "<body>").unwrap();
65 writeln!(&mut html, " <div id=\"swagger-ui\"></div>").unwrap();
66 writeln!(&mut html, " <script src=\"https://unpkg.com/swagger-ui-dist@5/swagger-ui-bundle.js\"></script>").unwrap();
67 writeln!(&mut html, " <script src=\"https://unpkg.com/swagger-ui-dist@5/swagger-ui-standalone-preset.js\"></script>")
68 .unwrap();
69 writeln!(&mut html, " <script>").unwrap();
70 writeln!(&mut html, " window.onload = function() {{").unwrap();
71 writeln!(&mut html, " const ui = SwaggerUIBundle({{").unwrap();
72 writeln!(&mut html, " url: '{}',", config.openapi_url).unwrap();
73 writeln!(&mut html, " dom_id: '#swagger-ui',").unwrap();
74 writeln!(&mut html, " deepLinking: true,").unwrap();
75 writeln!(&mut html, " presets: [").unwrap();
76 writeln!(&mut html, " SwaggerUIBundle.presets.apis,").unwrap();
77 writeln!(&mut html, " SwaggerUIStandalonePreset").unwrap();
78 writeln!(&mut html, " ],").unwrap();
79 writeln!(&mut html, " layout: 'StandaloneLayout'").unwrap();
80 writeln!(&mut html, " }});").unwrap();
81 writeln!(&mut html, " window.ui = ui;").unwrap();
82 writeln!(&mut html, " }};").unwrap();
83 writeln!(&mut html, " </script>").unwrap();
84 writeln!(&mut html, "</body>").unwrap();
85 writeln!(&mut html, "</html>").unwrap();
86 html
87}