我们的微服务接口调用方式支持grpc、http。在http请求接口的时候,每个服务要提供一个help接口,描述微服务接口信息。当在浏览器上请求服务的help接口时,要看到优美的样式。所以我们选择了markdown来描述hlep接口,接口返回时将markdown文本嵌入到能够展示markdown的html模板中。
我们希望做到的是代码与文档强绑定,不然文档与代码会不同步,文档也不会及时被维护。所以,将markdown的help描述文档直接编码到程序中,文档的修改更新与程序的发布紧密结合。具体实现时,可以将help信息保存到help.md文件中,在编译时将其转为资源文件。下文主要描述html模板的实现
使用showdown库解析markdown并生成html标签,然后使用github-markdown-css显示样式
两个库
- 解析markdown生成html标签 https://github.com/showdownjs/showdown
- github md的css样式 https://github.com/sindresorhus/github-markdown-css
js、css cdn链接
- https://cdnjs.cloudflare.com/ajax/libs/showdown/1.4.0/showdown.min.js
- https://cdnjs.cloudflare.com/ajax/libs/github-markdown-css/4.0.0/github-markdown.min.css
html模板
替换其中的${content}为markdown内容
<!DOCTYPE html>
<html>
<head>
<title>Markdown.js</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/github-markdown-css/4.0.0/github-markdown.min.css">
<style>
.markdown-body {
box-sizing: border-box;
min-width: 200px;
max-width: 980px;
margin: 0 auto;
padding: 45px;
}
@media (max-width: 767px) {
.markdown-body {
padding: 15px;
}
}
</style>
</head>
<body>
<div style="display:none" id="content">
${content}
</div>
<div id="show" class="markdown-body">
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/showdown/1.4.0/showdown.min.js"></script>
<script>
function html_decode(str) {
var s = "";
if (str.length == 0) return "";
s = str.replace(/&/g, "&");
s = s.replace(/</g, "<");
s = s.replace(/>/g, ">");
s = s.replace(/ /g, " ");
s = s.replace(/'/g, "\'");
s = s.replace(/"/g, "\"");
s = s.replace(/<br\/>/g, "\n");
return s;
}
var conv = new showdown.Converter({tables: true});
var txt = document.getElementById('content').innerHTML;
txt = html_decode(txt)
document.getElementById('show').innerHTML = conv.makeHtml(txt);
</script>
</html>
参考链接
- https://cloud.tencent.com/developer/article/1376436