为了账号安全,请及时绑定邮箱和手机立即绑定

在 Go 中的 README.md 中的注释标签之间插入链接

在 Go 中的 README.md 中的注释标签之间插入链接

Go
千万里不及你 2022-06-01 09:52:51
我想在我的README.md文件中的评论标签之间插入链接,因为我正在动态生成链接。我写了一个函数来做到这一点,但问题是它也替换了评论标签。我需要修改我的函数以插入评论标签之间的链接,而不是整体替换它。//README.md### HTTP APIs<!--HTTP-API-start--><!--HTTP-API-end-->### AMQP APIs<!--AMQP-API-start--><!--AMQP-API-end-->这是我为插入链接而编写的函数。一种可能的解决方案是将注释标签与字符串一起附加httpAPI,AmqpAPI但这不是我想要的,因为它替换了文件中的当前标签。func GenerateGodocLinkInReadme(amqpLinks string, httpLinks string) {    path := `../../README.md`    formattedContent, err := ioutil.ReadFile(path)    if err != nil {        panic(err)    }    httpAPI := "<!--HTTP-API-start-->" +        amqpLinks +        "\n" +        "<!--HTTP-API-end-->"    AmqpAPI := "<!--AMQP-API-start-->" +        httpLinks +        "\n" +        "<!--AMQP-API-end-->"    formattedContent = regexp.MustCompile(`<!--AMQP-API-start-->([\s\S]*?)<!--AMQP-API-end-->`).ReplaceAll(formattedContent, []byte(AmqpAPI))    exitOnFail(ioutil.WriteFile(path, formattedContent, 0644))    formattedContent = regexp.MustCompile(`<!--HTTP-API-start-->([\s\S]*?)<!--HTTP-API-end-->`).ReplaceAll(formattedContent, []byte(httpAPI))    exitOnFail(ioutil.WriteFile(path, formattedContent, 0644))}此功能正常工作,但它也替换了评论标签。我需要修改这个函数,以便它在评论标签之间插入链接。
查看完整描述

1 回答

?
月关宝盒

TA贡献1772条经验 获得超5个赞

尝试这个。


func GenerateGodocLinkInReadme(amqpLinks string, httpLinks string) {

    path := `README.md`

    formattedContent, err := ioutil.ReadFile(path)

    if err != nil {

        panic(err)

    }

    amqpRegex := regexp.MustCompile(`<!--AMQP-API-start-->([\s\S]*?)<!--AMQP-API-end-->`)

    httpRegex := regexp.MustCompile(`<!--HTTP-API-start-->([\s\S]*?)<!--HTTP-API-end-->`)


    prevAmqpLinks := string(amqpRegex.FindSubmatch((formattedContent))[1]) // Second index of returns links between tags

    prevHttpLinks := string(httpRegex.FindSubmatch((formattedContent))[1]) // Second index of returns links between tags

    httpAPI := prevHttpLinks + httpLinks + "\n"

    AmqpAPI := prevAmqpLinks + amqpLinks + "\n"

    formattedContent = amqpRegex.ReplaceAll(formattedContent, []byte(`<!--AMQP-API-start-->` + AmqpAPI + `<!--AMQP-API-end-->`))

    formattedContent = httpRegex.ReplaceAll(formattedContent, []byte(`<!--HTTP-API-start-->` + httpAPI + `<!--HTTP-API-end-->`))

    exitOnFail(ioutil.WriteFile(path, formattedContent, 0644))

}


查看完整回答
反对 回复 2022-06-01
  • 1 回答
  • 0 关注
  • 314 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号