Htmx allows us to handle async form submissions with ease by using hx-post attribute. In background it will issue a post request to the url specified in hx-post attribute and replace the element with the response.
Setup with Gofiber Initialize go module and install dependencies
go mod init htmx-form go get github.com/gofiber/fiber/v2 go get github.com/gofiber/template/html/v2 Setup Server
package main import ( "log" "github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2/log" "github.com/gofiber/template/html/v2" ) func main() { // Setup html template engine engine := html.New("./views", ".html") app := fiber.New(fiber.Config{ Views: engine, }) // Get request to render index page app.Get("/", func(c *fiber.Ctx) error { values := fiber.Map{ "EmailErr": "", "PasswordErr": "", "Success": "", "Error": "", } // Render index template return c.Render("index", values) }) // Post request to handle form submission app.Post("/form", func(c *fiber.Ctx) error { // Get form values email := c.FormValue("email") password := c.FormValue("password") // Setup values to be passed to template values := fiber.Map{ "EmailValue": email, "EmailErr": "", "PasswordErr": "", "Success": "", "Error": "", } // Validate form values if email == "" { values["EmailErr"] = "Email is required" } if password == "" { values["PasswordErr"] = "Password is required" } if email != "" && password != "" { values["EmailValue"] = "" values["Success"] = "Validation success" } else { values["Error"] = "Validation error" } // Render index template return c.Render("form", values) }) log.Fatal(app.Listen(":3000")) } Setup Views
...