让服务的help接口支持markdown显示

我们的微服务接口调用方式支持grpc、http。在http请求接口的时候,每个服务要提供一个help接口,描述微服务接口信息。当在浏览器上请求服务的help接口时,要看到优美的样式。所以我们选择了markdown来描述hlep接口,接口返回时将markdown文本嵌入到能够展示markdown的html模板中。
我们希望做到的是代码与文档强绑定,不然文档与代码会不同步,文档也不会及时被维护。所以,将markdown的help描述文档直接编码到程序中,文档的修改更新与程序的发布紧密结合。具体实现时,可以将help信息保存到help.md文件中,在编译时将其转为资源文件。下文主要描述html模板的实现


使用showdown库解析markdown并生成html标签,然后使用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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值