90 lines
1.9 KiB
Go
90 lines
1.9 KiB
Go
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"fmt"
|
|
"html/template"
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
"strings"
|
|
|
|
"github.com/gofiber/fiber/v2"
|
|
"github.com/gofiber/template/html/v2"
|
|
"github.com/yuin/goldmark"
|
|
"lmika.dev/web/isknow/models"
|
|
)
|
|
|
|
func main() {
|
|
questions := models.Game
|
|
|
|
prefix, _ := os.LookupEnv("PATH_PREFIX")
|
|
|
|
engine := html.New("./views", ".html")
|
|
engine.AddFunc("prefix", func() string { return prefix })
|
|
engine.AddFunc("markdown", func(s string) template.HTML {
|
|
if s == "" {
|
|
return ""
|
|
}
|
|
|
|
var buf bytes.Buffer
|
|
if err := goldmark.Convert([]byte(strings.TrimSpace(s)), &buf); err != nil {
|
|
return ""
|
|
}
|
|
return template.HTML(buf.String())
|
|
})
|
|
|
|
app := fiber.New(fiber.Config{
|
|
Views: engine,
|
|
ViewsLayout: "layout",
|
|
PassLocalsToViews: true,
|
|
})
|
|
|
|
app.Get("/", func(c *fiber.Ctx) error {
|
|
c.Locals("fadeIn", true)
|
|
return c.Render("index", fiber.Map{})
|
|
})
|
|
app.Get("/results", func(c *fiber.Ctx) error {
|
|
c.Locals("fadeIn", true)
|
|
return c.Render("results", fiber.Map{})
|
|
})
|
|
app.Get("/end", func(c *fiber.Ctx) error {
|
|
c.Locals("fadeIn", true)
|
|
return c.Render("end", fiber.Map{})
|
|
})
|
|
app.Get("/:qid", func(c *fiber.Ctx) error {
|
|
qID, err := c.ParamsInt("qid")
|
|
if err != nil {
|
|
return c.SendStatus(http.StatusBadRequest)
|
|
}
|
|
|
|
idx := qID - 1
|
|
if idx < 0 || idx >= len(questions.Questions) {
|
|
return c.SendStatus(http.StatusBadRequest)
|
|
}
|
|
|
|
rq, err := questions.Questions[idx].Render()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
nextURL := prefix + "/results"
|
|
reachedEnd := true
|
|
if idx+1 < len(questions.Questions) {
|
|
nextURL = fmt.Sprintf("%v/%d", prefix, idx+2)
|
|
reachedEnd = true
|
|
}
|
|
|
|
c.Locals("fadeIn", idx == 0)
|
|
return c.Render("question", fiber.Map{
|
|
"q": rq,
|
|
"qIdx": qID,
|
|
"nextURL": nextURL,
|
|
"reachedEnd": reachedEnd,
|
|
})
|
|
})
|
|
app.Static("/assets", "./public")
|
|
|
|
log.Fatal(app.Listen(":3000"))
|
|
}
|