58 lines
1.4 KiB
Go
58 lines
1.4 KiB
Go
package blog
|
|
|
|
import (
|
|
"github.com/gomarkdown/markdown"
|
|
"github.com/gomarkdown/markdown/html"
|
|
"github.com/gomarkdown/markdown/parser"
|
|
"html/template"
|
|
"regexp"
|
|
"time"
|
|
)
|
|
|
|
func makePost(markdownContent []byte) Post {
|
|
headerRegex := regexp.MustCompile(`(?ms)^---\n.*?---`)
|
|
header := headerRegex.Find(markdownContent)
|
|
headerKeysRegex := regexp.MustCompile(`(?m)^(\w+): ([^\n]*)$`)
|
|
headerKeys := headerKeysRegex.FindAllSubmatch(header, -1)
|
|
postBody := headerRegex.ReplaceAll(markdownContent, []byte(""))
|
|
|
|
post := Post{}
|
|
|
|
for _, headerKey := range headerKeys {
|
|
key, value := string(headerKey[1]), string(headerKey[2])
|
|
switch key {
|
|
case "title":
|
|
post.Title = value
|
|
case "date":
|
|
date, err := time.Parse(time.DateOnly, value)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
post.Date = date
|
|
case "updatedDate":
|
|
date, err := time.Parse(time.DateOnly, value)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
post.UpdatedDate = date
|
|
case "author":
|
|
post.Author = value
|
|
case "slug":
|
|
post.Slug = value
|
|
}
|
|
}
|
|
|
|
extensions := parser.CommonExtensions | parser.AutoHeadingIDs | parser.NoEmptyLineBeforeBlock
|
|
p := parser.NewWithExtensions(extensions)
|
|
doc := p.Parse(postBody)
|
|
|
|
// create HTML renderer with extensions
|
|
htmlFlags := html.CommonFlags | html.HrefTargetBlank
|
|
opts := html.RendererOptions{Flags: htmlFlags}
|
|
renderer := html.NewRenderer(opts)
|
|
|
|
post.Body = template.HTML(markdown.Render(doc, renderer))
|
|
|
|
return post
|
|
}
|