65 lines
1.3 KiB
Go
65 lines
1.3 KiB
Go
package models
|
|
|
|
import (
|
|
"bytes"
|
|
"io/ioutil"
|
|
"log"
|
|
"os"
|
|
"strings"
|
|
|
|
"github.com/yuin/goldmark"
|
|
meta "github.com/yuin/goldmark-meta"
|
|
"github.com/yuin/goldmark/extension"
|
|
"github.com/yuin/goldmark/parser"
|
|
"github.com/yuin/goldmark/renderer/html"
|
|
)
|
|
|
|
type Article struct {
|
|
Title string
|
|
HtmlContent string
|
|
publishedDate string
|
|
Url string
|
|
File string
|
|
RelativeFilePath string
|
|
}
|
|
|
|
func (a *Article) FromFile() {
|
|
// Build an Article based on a file path
|
|
|
|
content, err := os.ReadFile(a.File)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
a.FromContent(content)
|
|
}
|
|
|
|
func (a *Article) FromContent(content []byte) {
|
|
// Build an Article instance from a byte[] content
|
|
|
|
md := goldmark.New(
|
|
goldmark.WithExtensions(extension.GFM, meta.Meta),
|
|
goldmark.WithParserOptions(
|
|
parser.WithAutoHeadingID(),
|
|
),
|
|
goldmark.WithRendererOptions(
|
|
html.WithHardWraps(),
|
|
html.WithXHTML(),
|
|
),
|
|
)
|
|
|
|
var buf bytes.Buffer
|
|
context := parser.NewContext()
|
|
if err := md.Convert(content, &buf, parser.WithContext(context)); err != nil {
|
|
panic(err)
|
|
}
|
|
a.HtmlContent = buf.String()
|
|
metadata := meta.Get(context)
|
|
a.Title, _ = metadata["Title"].(string)
|
|
}
|
|
|
|
func (a Article) Write() {
|
|
outputFilePath := strings.Replace(a.File, ".md", ".html", -1)
|
|
ioutil.WriteFile(outputFilePath, []byte(a.HtmlContent), 0644)
|
|
}
|