website/routes/news.go
2023-12-09 19:25:38 +03:00

93 lines
1.9 KiB
Go

package routes
import (
"encoding/json"
"os"
"path"
"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: %s", err)
return RenderError(c, 500)
}
err = json.Unmarshal(jsonc, &con)
if err != nil {
log.Errorf("Cannot parse news JSON: %s", err)
return RenderError(c, 500)
}
res = append(res, con)
}
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)
}