md-view-go/util/FileUtil.go

101 lines
2.4 KiB
Go

package util
import (
"html/template"
"os"
"path/filepath"
"sort"
"strings"
"github.com/gomarkdown/markdown"
"github.com/gomarkdown/markdown/html"
"github.com/gomarkdown/markdown/parser"
"github.com/spf13/viper"
)
func GetMdStr(path string) template.HTML {
fileMeta, err := os.Stat(path)
if err != nil {
return "读取错误"
}
if fileMeta.IsDir() {
return GetDirStr(path)
} else {
context, err := os.ReadFile(path)
if err != nil {
return "error"
}
htmlContext := MdToHtml(context)
html := template.HTML(htmlContext)
return html
}
}
func GetDirStr(path string) template.HTML {
listResult := GetFileList(path)
context := ""
for i := 0; i < len(listResult); i++ {
item := listResult[i]
if !strings.HasPrefix(item.FileName, ".") && item.FileName != "assets" {
context += "- [" + item.FileName + "](" + item.FilePath + ") \n"
}
}
htmlContext := MdToHtml([]byte(context))
html := template.HTML(htmlContext)
return html
}
func GetFileList(path string) []FileModel {
var result []FileModel
fileMeta, err := os.Stat(path)
if err != nil {
return result
}
rootDir := viper.GetString("dir.root")
if !fileMeta.IsDir() {
path = filepath.Dir(path)
}
list, err := os.ReadDir(path)
if err != nil {
return result
}
for i := 0; i < len(list); i++ {
item := list[i]
fileInfo, err := item.Info()
//fmt.Println(fileInfo.Name())
if err != nil {
continue
}
if strings.HasPrefix(fileInfo.Name(), ".") || fileInfo.Name() == "assets" {
continue
}
if !strings.HasSuffix(path, "/") {
path = path + "/"
}
filePath := strings.Replace(path+fileInfo.Name(), rootDir, "", -1)
if !strings.HasPrefix(filePath, "/") {
filePath = "/" + filePath
}
result = append(result, FileModel{FileName: fileInfo.Name(), FilePath: filePath})
}
// 用 age 排序,年龄相等的元素保持原始顺序
sort.SliceStable(result, func(i, j int) bool {
return result[i].FileName < result[j].FileName
})
return result
}
func MdToHtml(context []byte) []byte {
// create markdown parser with extensions
extensions := parser.CommonExtensions | parser.AutoHeadingIDs | parser.NoEmptyLineBeforeBlock
p := parser.NewWithExtensions(extensions)
doc := p.Parse(context)
// create HTML renderer with extensions
htmlFlags := html.CommonFlags | html.HrefTargetBlank
opts := html.RendererOptions{Flags: htmlFlags}
renderer := html.NewRenderer(opts)
return markdown.Render(doc, renderer)
}