【go语言】编写一款markdown解析插件,通过wasm给前端调用

本文介绍了如何使用Go语言编写一个Markdown转HTML的函数,并将其编译为WASM,然后在前端通过JavaScript调用,实现了一个简单的Markdown转换器并在静态服务器上展示效果。
摘要由CSDN通过智能技术生成

背景

wasm作为一种通用的文件格式,可以通过编程语言A实现一个功能, 给语言B调用。那么,接下来,通过go语言实现一个markdown转html的功能插件, 然后在html中调用。

环境相关

  • go 1.21.0(window10测试通过)
  • linux下vscode会报错:imports syscall/js: build constraints exclude all Go files in /home/coder/sdk/go1.22.3/src/syscall/js, 编译先指定架构使用GOOS=js GOARCH=wasm go build -o dist/output.wasm

步骤

1. 编写main.go

markdownToHTML: 将输入的markdown文本转化为html。

package main

import (
	"github.com/russross/blackfriday/v2"
	"syscall/js"
)

func markdownToHTML(this js.Value, inputs []js.Value) interface{} {
	markdown := inputs[0].String()
	html := blackfriday.Run([]byte(markdown))
	return js.ValueOf(string(html))
}

func registerCallbacks() {
	js.Global().Set("markdownToHTML", js.FuncOf(markdownToHTML))
}

func main() {
	c := make(chan struct{}, 0)

	registerCallbacks()

	<-c
}

2. 编译为wasm

windows下, 执行下面build,生成output.wasm

set GOOS=js
set GOARCH=wasm
go build -o build\output.wasm

在这里插入图片描述

3. 编写前端代码,目录结构如下

在这里插入图片描述

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Markdown to HTML</title>
</head>
<body>
<button onclick="convertMarkdown()">Convert</button>
<div style="display: flex;width: 100%;justify-content: space-around">
    <textarea style="width: 48%" id="markdown-input" cols="80" rows="10"># Hello, Markdown!</textarea>
    <div style="width: 48%" id="html-output"></div>
</div>
<script src="wasm_exec.js"></script>
<script>
    const go = new Go();
    let mod, inst;
    WebAssembly.instantiateStreaming(fetch('output.wasm'), go.importObject).then((result) => {
        mod = result.module;
        inst = result.instance;
        go.run(inst);
    });

    async function convertMarkdown() {
        const markdownInput = document.getElementById('markdown-input').value;

        const markdownToHTML = globalThis.markdownToHTML;
        const htmlOutput = markdownToHTML(markdownInput);

        console.log(htmlOutput)

        document.getElementById('html-output').innerHTML = htmlOutput;
    }
</script>
</body>
</html>

wasm_exec.js

从你本地 GO安装目录\misc\wasm\下复制

output.wasm

刚刚build出的产物

打开静态服务器,查看最终效果

npm install -g serve
serve -s public 

访问127.0.0.1:3000
基本都能转换为对应的html标签,但是没有样式。
ok一个小功能就完成了。
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值