aboutsummaryrefslogtreecommitdiff
path: root/backend/parser.go
blob: a0cb01fa8135c6b3932721212d1383635653b7da (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package backend

import (
	"errors"
	"fmt"
	"html/template"
	"log/slog"
	"strings"

	"git.anhgelus.world/anhgelus/small-world/markdown"
	"github.com/pelletier/go-toml/v2"
)

type EntryInfo struct {
	Title        string         `toml:"title"`
	Description  string         `toml:"description"`
	Img          image          `toml:"image"`
	PubLocalDate toml.LocalDate `toml:"publication_date"`
}

func parse(b []byte, info *EntryInfo) (template.HTML, bool) {
	var dd string
	splits := strings.SplitN(string(b), "---", 2)
	if len(splits) == 2 && info != nil {
		err := toml.Unmarshal([]byte(splits[0]), info)
		if err != nil {
			slog.Warn("parsing entry info", "error", err)
		} else {
			dd = splits[1]
		}
	} else {
		dd = string(b)
	}
	content, err := markdown.Parse(dd, &markdown.Option{ImageSource: getStatic})
	var errMd *markdown.ParseError
	errors.As(err, &errMd)
	if errMd != nil {
		slog.Error("parsing markdown")
		fmt.Println(errMd.Pretty())
		return "", false
	}
	return content, true
}