Files
fiber-sessions/app/handlers/interactive.go
Eden Kirin c0f161abe1 Initial
2024-02-05 22:30:11 +01:00

92 lines
2.2 KiB
Go

package handlers
import (
"fiber-sessions/app/data"
"fiber-sessions/app/templates"
"fiber-sessions/app/types"
"strconv"
"strings"
"github.com/gofiber/fiber/v2"
)
var pcInteractive templates.PageContext = templates.PageContext{
Title: "Welcome to the demo - Interactive",
ActivePage: "interactive",
}
func Interactive(f *fiber.Ctx) error {
Render(f, templates.Interactive(pcInteractive, data.CatBreeds))
return nil
}
func InteractiveSwapContent(f *fiber.Ctx) error {
contentIndexStr := f.Query("content")
contentIndex, err := strconv.Atoi(contentIndexStr)
if err != nil {
contentIndex = 0
}
Render(f, templates.InteractiveSwapContent(pcInteractive, contentIndex))
return nil
}
func FilterCatBreeds(f *fiber.Ctx) error {
breedQuery := strings.ToLower(f.Query("breed"))
countryQuery := f.Query("country")
var catBreeds []types.CatBreed = []types.CatBreed{}
for _, cb := range data.CatBreeds {
appendToList :=
(len(breedQuery) > 0 &&
strings.Contains(strings.ToLower(cb.Breed), breedQuery) ||
len(breedQuery) == 0) &&
((len(countryQuery) > 0 &&
cb.Country == countryQuery) ||
len(countryQuery) == 0)
if appendToList {
catBreeds = append(catBreeds, cb)
}
}
Render(f, templates.RenderCatBreedsTable(catBreeds))
return nil
}
func ValidateForm(f *fiber.Ctx) error {
content := templates.ValidateFormContent{
Validated: true,
NumValue: f.FormValue("number-value"),
StrValue: f.FormValue("string-value"),
}
numValue, err := strconv.Atoi(content.NumValue)
if err != nil {
content.HasNumValueError = true
content.NumValueError = "This is not valid number"
}
if !content.HasNumValueError {
if numValue < 0 {
content.HasNumValueError = true
content.NumValueError = "Value is less than 0"
}
if numValue > 100 {
content.HasNumValueError = true
content.NumValueError = "Value is greater than 100"
}
}
if len(content.StrValue) < 5 {
content.HasStrValueError = true
content.StrValueError = "String length is less than 5"
}
if len(content.StrValue) > 10 {
content.HasStrValueError = true
content.StrValueError = "String length is more than 10"
}
Render(f, templates.RenderInteractiveForm(content))
return nil
}