基于Go語(yǔ)言開發(fā)一個(gè)Markdown轉(zhuǎn)HTML工具
這個(gè)小工具可以把 .md 文件轉(zhuǎn)換為 .html 文件,非常適合寫筆記、博客或者快速預(yù)覽 Markdown 內(nèi)容。
案例目標(biāo)
- 讀取一個(gè) Markdown 文件
- 使用開源庫(kù)將 Markdown 轉(zhuǎn)換為 HTML
- 將 HTML 輸出到新文件中
所需庫(kù)
我們用 goldmark 這個(gè) Markdown 解析庫(kù),它輕量且高效。
安裝:
go get github.com/yuin/goldmark
實(shí)現(xiàn)代碼
package main
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"github.com/yuin/goldmark"
)
func main() {
if len(os.Args) < 2 {
fmt.Println("用法: go run main.go <markdown文件>")
return
}
mdFile := os.Args[1]
// 讀取Markdown文件
content, err := ioutil.ReadFile(mdFile)
if err != nil {
fmt.Printf("讀取文件失敗: %v\n", err)
return
}
// 轉(zhuǎn)換為HTML
var htmlOutput []byte
md := goldmark.New()
var buf []byte
htmlBuf := &buf
err = md.Convert(content, htmlBuf)
if err != nil {
fmt.Printf("Markdown 轉(zhuǎn)換失敗: %v\n", err)
return
}
htmlOutput = *htmlBuf
// 生成HTML文件名
htmlFile := filepath.Base(mdFile[:len(mdFile)-len(filepath.Ext(mdFile))]) + ".html"
// 寫入HTML文件
err = ioutil.WriteFile(htmlFile, htmlOutput, 0644)
if err != nil {
fmt.Printf("寫入HTML文件失敗: %v\n", err)
return
}
fmt.Printf("轉(zhuǎn)換成功!輸出文件: %s\n", htmlFile)
}
使用方法
保存代碼為 main.go
準(zhǔn)備一個(gè) test.md 文件,例如:
# Hello Markdown
這是一個(gè) **Markdown 轉(zhuǎn) HTML** 的測(cè)試。
- 項(xiàng)目一
- 項(xiàng)目二
運(yùn)行:
go run main.go test.md
會(huì)生成 test.html,在瀏覽器里打開就能看到格式化的內(nèi)容
方法補(bǔ)充
golang 自定義解析 markdown為 html
輸出 HTML 模板內(nèi)容如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Custom Markdown</title>
<link rel="stylesheet" href="markdown.css" rel="external nofollow" />
</head>
<body>
{{ . }}
</body>
</html>
golang 程序如下
安裝依賴 go get -u github.com/gomarkdown/markdown
package main
import (
"bufio"
"github.com/gomarkdown/markdown"
"github.com/gomarkdown/markdown/ast"
"github.com/gomarkdown/markdown/html"
"html/template"
"io"
"log"
"os"
)
// return (ast.GoToNext, true) to tell html renderer to skip rendering this node
// (because you've rendered it)
func renderHookCodeBlock(w io.Writer, node ast.Node, entering bool) (ast.WalkStatus, bool) {
// skip all nodes that are not CodeBlock nodes
if _, ok := node.(*ast.CodeBlock); !ok {
return ast.GoToNext, false
}
// custom rendering logic for ast.CodeBlock. By doing nothing it won't be
// 寫入自定義數(shù)據(jù)
w.Write([]byte(`<span>Hello World</span>`))
return ast.GoToNext, false
}
func main() {
inputFile := "markdown.md" // 輸入 md 文件
inputTemplateFile := "template.html" // 模板文件
outputFile := "markdown.html" // 輸出 html 文件
opts := html.RendererOptions{
Flags: html.CommonFlags,
RenderNodeHook: renderHookCodeBlock, // 設(shè)置自定義處理鉤子
}
renderer := html.NewRenderer(opts)
// 打開 md 文件
fs, err := os.Open(inputFile)
if err != nil {
return
}
// 讀取 md 內(nèi)容
var md string
scanner := bufio.NewScanner(fs)
for scanner.Scan() {
md += scanner.Text() + "\n"
}
if scanner.Err() != nil {
log.Panicln(err)
}
// md to html
html := markdown.ToHTML([]byte(md), nil, renderer)
tp, err := template.ParseFiles(inputTemplateFile)
if err != nil {
return
}
// 寫入輸出文件
f, err := os.Create(outputFile)
if err != nil {
return
}
tp.Execute(f, template.HTML(html))
print(string(html))
}
到此這篇關(guān)于基于Go語(yǔ)言開發(fā)一個(gè)Markdown轉(zhuǎn)HTML工具的文章就介紹到這了,更多相關(guān)Go Markdown轉(zhuǎn)HTML內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Golang 處理浮點(diǎn)數(shù)遇到的精度問(wèn)題(使用decimal)
本文主要介紹了Golang 處理浮點(diǎn)數(shù)遇到的精度問(wèn)題,不使用decimal會(huì)出大問(wèn)題,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-02-02
Go語(yǔ)言Elasticsearch數(shù)據(jù)清理工具思路詳解
這篇文章主要介紹了Go語(yǔ)言Elasticsearch數(shù)據(jù)清理工具思路詳解,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-10-10
Go中Goroutines輕量級(jí)并發(fā)的特性及效率探究
這篇文章主要為大家介紹了Go中Goroutines輕量級(jí)并發(fā)的特性及效率探究,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-12-12
Golang實(shí)現(xiàn)文件夾的創(chuàng)建與刪除的方法詳解
這篇文章主要介紹了如何利用Go語(yǔ)言實(shí)現(xiàn)對(duì)文件夾的常用操作:創(chuàng)建于刪除。文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2022-05-05
Windows上安裝Go并配置環(huán)境變量(圖文步驟)
開始使用Go創(chuàng)建應(yīng)用程序之前,需要設(shè)置開發(fā)環(huán)境,本文主要介紹了Windows上安裝Go并配置環(huán)境變量,具有一定的參考價(jià)值,感興趣的可以了解一下2023-08-08
golang中channel+error來(lái)做異步錯(cuò)誤處理有多香
官方推薦golang中錯(cuò)誤處理當(dāng)做值處理, 既然是值那就可以在channel中傳輸,這篇文章主要介紹了golang 錯(cuò)誤處理channel+error真的香,需要的朋友可以參考下2023-01-01

