103 lines
2.2 KiB
Go
103 lines
2.2 KiB
Go
package routes
|
|
|
|
import (
|
|
"encoding/json"
|
|
"os"
|
|
"path"
|
|
"sort"
|
|
"strings"
|
|
|
|
"github.com/gofiber/fiber/v2"
|
|
"github.com/gofiber/fiber/v2/log"
|
|
)
|
|
|
|
var news_path = path.Join("content", "news")
|
|
|
|
func NewsRoute(c *fiber.Ctx) error {
|
|
var res []Content
|
|
entries, err := os.ReadDir(news_path)
|
|
if err != nil {
|
|
log.Errorf("Cannot news dir: %s", err)
|
|
return RenderError(c, 500)
|
|
}
|
|
|
|
for _, e := range entries {
|
|
if(!strings.HasSuffix(e.Name(), ".json")) {
|
|
continue
|
|
}
|
|
|
|
var con Content
|
|
jsonc, err := os.ReadFile(path.Join(news_path, e.Name()))
|
|
if err != nil {
|
|
log.Errorf("Cannot news JSON for %s: %s", e.Name(), err)
|
|
return RenderError(c, 500)
|
|
}
|
|
err = json.Unmarshal(jsonc, &con)
|
|
if err != nil {
|
|
log.Errorf("Cannot parse news JSON for %s: %s", e.Name(), err)
|
|
return RenderError(c, 500)
|
|
}
|
|
|
|
con.Time, err = TimeFromString(con.Date)
|
|
if err != nil {
|
|
log.Errorf("Cannot parse time for '%s': %s", con.Name, err)
|
|
}
|
|
res = append(res, con)
|
|
|
|
}
|
|
|
|
sort.Slice(res, func(i, j int) bool {
|
|
return res[i].Time.After(res[j].Time)
|
|
})
|
|
|
|
return c.Render("news", fiber.Map{
|
|
"news": res,
|
|
})
|
|
}
|
|
|
|
func PostRoute(c *fiber.Ctx) error {
|
|
postid := c.Params("id")
|
|
if len(postid) == 0 {
|
|
return RenderError(c, 404)
|
|
}
|
|
|
|
var res Content
|
|
entries, err := os.ReadDir(news_path)
|
|
if err != nil {
|
|
log.Errorf("Cannot news dir: %s", err)
|
|
return RenderError(c, 500)
|
|
}
|
|
|
|
for _, e := range entries {
|
|
if(!strings.HasSuffix(e.Name(), ".json")) {
|
|
continue
|
|
}
|
|
|
|
jsonc, err := os.ReadFile(path.Join(news_path, e.Name()))
|
|
if err != nil {
|
|
log.Errorf("Cannot news JSON: %s", err)
|
|
return RenderError(c, 500)
|
|
}
|
|
|
|
err = json.Unmarshal(jsonc, &res)
|
|
if err != nil {
|
|
log.Errorf("Cannot parse news JSON: %s", err)
|
|
return RenderError(c, 500)
|
|
}
|
|
|
|
if(res.ID == postid) {
|
|
res, err = GetContent(news_path, strings.Split(e.Name(), ".json")[0])
|
|
if err != nil {
|
|
log.Errorf("Cannot get content: %s", err)
|
|
return RenderError(c, 500)
|
|
}
|
|
|
|
return c.Render("post", fiber.Map{
|
|
"post": res,
|
|
})
|
|
}
|
|
}
|
|
|
|
return RenderError(c, 404)
|
|
}
|