use hypers_core::{
async_trait,
prelude::{Request, Response, Text},
Handler,
};
use std::borrow::Cow;
#[non_exhaustive]
#[derive(Clone, Debug)]
pub struct RapiDoc {
pub title: Cow<'static, str>,
pub keywords: Option<Cow<'static, str>>,
pub description: Option<Cow<'static, str>>,
pub lib_url: Cow<'static, str>,
pub spec_url: Cow<'static, str>,
}
impl RapiDoc {
pub fn new(spec_url: impl Into<Cow<'static, str>>) -> Self {
Self {
title: "RapiDoc".into(),
keywords: None,
description: None,
lib_url: "https://unpkg.com/rapidoc/dist/rapidoc-min.js".into(),
spec_url: spec_url.into(),
}
}
pub fn title(mut self, title: impl Into<Cow<'static, str>>) -> Self {
self.title = title.into();
self
}
pub fn keywords(mut self, keywords: impl Into<Cow<'static, str>>) -> Self {
self.keywords = Some(keywords.into());
self
}
pub fn description(mut self, description: impl Into<Cow<'static, str>>) -> Self {
self.description = Some(description.into());
self
}
pub fn lib_url(mut self, lib_url: impl Into<Cow<'static, str>>) -> Self {
self.lib_url = lib_url.into();
self
}
}
#[async_trait]
impl Handler for RapiDoc {
#[inline]
async fn handle(&self, _: Request) -> Response {
let keywords = self
.keywords
.as_ref()
.map(|s| {
format!(
"<meta name=\"keywords\" content=\"{}\">",
s.split(',').map(|s| s.trim()).collect::<Vec<_>>().join(",")
)
})
.unwrap_or_default();
let description = self
.description
.as_ref()
.map(|s| format!("<meta name=\"description\" content=\"{}\">", s))
.unwrap_or_default();
let html = r#"
<!doctype html>
<html>
<head>
<title>{{title}}</title>
{{keywords}}
{{description}}
<meta charset="utf-8">
<script type="module" src="{{lib_url}}"></script>
</head>
<body>
<rapi-doc spec-url="{{spec_url}}"></rapi-doc>
</body>
</html>
"#
.replacen("{{spec_url}}", &self.spec_url, 1)
.replacen("{{lib_url}}", &self.lib_url, 1)
.replacen("{{description}}", &description, 1)
.replacen("{{keywords}}", &keywords, 1)
.replacen("{{title}}", &self.title, 1);
Response::default().render(Text::Html(html))
}
}