website/routes/util.go

59 lines
1.3 KiB
Go
Raw Normal View History

2023-12-09 16:25:38 +00:00
package routes
import (
"encoding/json"
"errors"
"html/template"
"os"
"path"
"github.com/gofiber/fiber/v2"
"github.com/russross/blackfriday/v2"
)
type Content struct {
ID string `json:"id"`
Name string `json:"name"`
Date string `json:"date"`
Author string `json:"author"`
Content template.HTML `json:"content"`
}
func GetContent(pth string, name string) (Content, error) {
var res Content
jsonfile := path.Join(pth, name+".json")
mdfile := path.Join(pth, name+".md")
jsoncontent, err := os.ReadFile(jsonfile)
if err != nil {
return res, errors.New("Cannot read JSON file: "+jsonfile)
}
mdcontent, 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)
}
md := string(blackfriday.Run(mdcontent, blackfriday.WithExtensions(blackfriday.BackslashLineBreak)))
res.Content = template.HTML(md)
return res, nil
}
func RenderError(c *fiber.Ctx, code int) error{
var msg string = "Server Error"
c.Status(code)
switch code {
case 404:
msg = "Not Found"
}
return c.Render("error", fiber.Map{
"msg": msg,
})
}