package main import ( "fmt" "log" "net/http" "os" "github.com/gofiber/fiber/v2" "github.com/gofiber/template/html/v2" "lmika.dev/web/isknow/models" ) func main() { questions := models.QuestionSet{ Questions: []models.Question{ { ID: "1", Text: "What is 1 + 1?", Choices: []models.Choice{ {Text: "1"}, {Text: "2", IsRight: true}, {Text: "3"}, {Text: "4"}, }, Fact: "1 + 1 = 2", }, { ID: "2", Text: "What is 3 * 5?", Choices: []models.Choice{ {Text: "5"}, {Text: "10"}, {Text: "15", IsRight: true}, {Text: "20"}, }, Fact: "I can't use the iPad for coding this", }, }, } prefix, _ := os.LookupEnv("PATH_PREFIX") engine := html.New("./views", ".html") engine.AddFunc("prefix", func() string { return prefix }) app := fiber.New(fiber.Config{ Views: engine, ViewsLayout: "layout", }) app.Get("/", func(c *fiber.Ctx) error { return c.Render("index", fiber.Map{}) }) app.Get("/end", func(c *fiber.Ctx) error { 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 + "/end" reachedEnd := true if idx+1 < len(questions.Questions) { nextURL = fmt.Sprintf("%v/%d", prefix, idx+2) reachedEnd = true } return c.Render("question", fiber.Map{ "q": rq, "nextURL": nextURL, "reachedEnd": reachedEnd, }) }) app.Static("/assets", "./public") log.Fatal(app.Listen(":3000")) }