Go: how to handle form submission with Fiber

When developing web applications, one of the most common functionalities is form handling. In this article, we will explore how to handle form submission via POST using Fiber, a web framework for Go. Fiber is known for its simplicity and speed, making it an excellent choice for Go projects.

Before we start, make sure you have Go installed on your system. You can download it from the official Go website. Additionally, you will need to install Fiber. You can do this using the command:


go get -u github.com/gofiber/fiber/v2

Let's begin by creating a simple Fiber application. Open your favorite text editor and create a new file called main.go. Add the following code to set up a new Fiber application:


package main

import (
    "github.com/gofiber/fiber/v2"
)

func main() {
    app := fiber.New()

    app.Get("/", func(c *fiber.Ctx) error {
        return c.SendString("Hello, World!")
    })

    app.Listen(":3000")
}

This code creates a new Fiber application and starts a server on port 3000 that responds with "Hello, World!" when accessing the root (/).

To handle form submission, we will need a simple HTML form. Let's update our handler for the root route to return an HTML form:


app.Get("/", func(c *fiber.Ctx) error {
    form := `
        <form action="/submit" method="POST">
            <label for="name">Name:</label>
            <input type="text" id="name" name="name">
            <input type="submit" value="Submit">
        </form>
    `
    return c.SendString(form)
})

Now, let's add a new route to handle form submission. We will use a handler that reads the data submitted in the form and displays it:


app.Post("/submit", func(c *fiber.Ctx) error {
    name := c.FormValue("name")
    response := "Hello, " + name
    return c.SendString(response)
})

Conclusion

We have seen how to create a simple web application with Fiber in Go that handles form submission via POST. Fiber makes this process very straightforward and easy thanks to its intuitive API. From here, you can extend your application to handle more complex forms, validate input, and persist data in a database.

Back to top