website/lib/content.go

97 lines
1.9 KiB
Go
Raw Permalink Normal View History

package lib
import (
"encoding/json"
"errors"
"html/template"
"os"
"path"
"strings"
)
const CONTENT_PATH string = "content"
2024-08-13 21:32:48 +00:00
type Content struct {
Dir string
Name string
2024-08-13 21:32:48 +00:00
Title string `json:"title"`
ID string `json:"id"`
2024-08-13 21:32:48 +00:00
Md string
HTML template.HTML
2024-08-13 21:32:48 +00:00
Date string `json:"date"`
Author string `json:"author"`
}
func ListContent(dir string) ([]Content, error) {
2024-08-13 21:32:48 +00:00
var res []Content
dirpath := path.Join(CONTENT_PATH, dir)
entries, err := os.ReadDir(dirpath)
if err != nil {
return nil, errors.New("Cannot readdir: " + dirpath)
}
for _, e := range entries {
if e.IsDir() {
subres, err := ListContent(path.Join(dir, e.Name()))
if err != nil {
return res, err
}
res = append(res, subres...)
}
if !strings.HasSuffix(e.Name(), ".json") {
continue
}
var con Content
jsonfile := path.Join(dirpath, e.Name())
jsoncon, err := os.ReadFile(jsonfile)
if err != nil {
return nil, errors.New("Cannot get JSON: " + jsonfile)
}
err = json.Unmarshal(jsoncon, &con)
if err != nil {
return nil, errors.New("Cannot parse JSON: " + jsonfile)
}
con.Dir = dir
con.Name = strings.Split(e.Name(), ".")[0]
res = append(res, con)
}
return res, nil
}
func GetContent(dir string, name string) (Content, error) {
2024-08-13 21:32:48 +00:00
var res Content
jsonfile := path.Join(CONTENT_PATH, dir, name+".json")
mdfile := path.Join(CONTENT_PATH, dir, name+".md")
res.Dir = dir
res.Name = name
jsoncontent, err := os.ReadFile(jsonfile)
if err != nil {
return res, errors.New("Cannot read JSON file: " + jsonfile)
}
rawcontent, err := os.ReadFile(mdfile)
if err != nil {
return res, errors.New("Cannot read markdown file: " + mdfile)
}
if json.Unmarshal(jsoncontent, &res) != nil {
return res, errors.New("Cannot parse JSON: " + jsonfile)
}
res.Md = string(rawcontent)
res.HTML = template.HTML(ParseMarkdown(res.Md))
return res, nil
}