How to Create Web Applications using Go Fiber 2023

Go: Fiber Web Framework

What is Fiber Web Framework?

Fiber framework is a lightweight, open-source web framework for Golang. It is designed to be fast, flexible, and easy to use, making it a popular choice for building web applications. Fiber framework provides a range of features, including routing, middleware, and error handling, which help developers to quickly build robust and scalable web applications.

The combination of Golang and Fiber framework provides developers with a powerful set of tools for building web applications.

Golang's built-in concurrency and fast compilation times make it a great choice for building web applications that need to handle high traffic. Meanwhile, Fiber framework's easy-to-use APIs and built-in middleware make it a great choice for building web applications quickly and efficiently.

In this blog post, we will walk you through the process of creating a simple web application using Golang and Fiber framework.

1.Setting up the Development Environment

Before we start building web applications using Golang and Fiber framework, we need to set up our development environment. Here are the steps we need to follow:

  • Install Golang: You can download and install Golang from the official website. Once you have installed Golang, you can verify the installation by running the command go version in your terminal.

  • Install Fiber framework: You can install Fiber framework using the command go get -u github.com/gofiber/fiber/v2. This will download and install the latest version of Fiber framework on your machine.

  • Set up your project: Once you have installed Golang and Fiber framework, you can set up your project by creating a new directory and initializing it as a Golang module using the command go mod init <module name>.

2. Creating a Simple Web Application with Fiber Framework

Now that you have set up your development environment, you can start creating your web application using Fiber framework. Here are the steps you need to follow:

  • Create a new Fiber application: We can create a new instance of the Fiber struct using the command app := fiber.New().
    package main

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

    func main() {
        app := fiber.New()
    }
  • Define a route: We can define a route using the HTTP method GET and the path / using the command app.Get("/", handler). The handler function will be called when the route is accessed. In our case, the handler function will return a greeting message.
    func handler(c *fiber.Ctx) error {
        return c.SendString("Hello, World!")
    }

    func main() {
        app := fiber.New()
        app.Get("/", handler)
    }
  • Start the server: We can start the server using the command app.Listen(port). The server will start listening for incoming requests on the specified port. In our case, we will listen on port 3000.
    func main() {
        app := fiber.New()
        app.Get("/", handler)

        app.Listen(":3000")
    }

With these steps completed, we have created a simple web application that greets the user with a message.

3. Adding Middleware to Your Web Application

Middleware functions are functions that are executed in between the request and the response. They can be used for a variety of purposes such as logging, authentication, and error handling. Fiber framework provides a simple and efficient way of adding middleware to your web application. Here are the steps you need to follow:

  • Define a middleware function: We can define a middleware function that logs the incoming request using the command func logRequest(c *fiber.Ctx) error.
    func logRequest(c *fiber.Ctx) error {
        log.Printf("%s %s\n", c.Method(), c.Path())
        return c.Next()
    }
  • Register the middleware function: We can register the middleware function using the command app.Use(logRequest). The middleware function will be executed for every incoming request before the route handler function is called.
    func main() {
        app := fiber.New()

        app.Use(logRequest)

        app.Get("/", handler)

        app.Listen(":3000")
    }
  • Chain middleware functions: We can chain multiple middleware functions by adding them as additional arguments to the Use() function. In our example, we can chain the logRequest() function with the built-in logger middleware function using the command app.Use(logger.New(), logRequest).
    func main() {
        app := fiber.New()

        app.Use(logger.New())
        app.Use(logRequest)

        app.Get("/", handler)

        app.Listen(":3000")
    }

With these steps completed, we have added a middleware function that logs each incoming request to our simple web application.

4: Parsing Request Data in Your Web Application

Parsing request data is a common task in web development. In Fiber framework, you can easily parse request data by using the context object.

Here are the steps you need to follow:

  • Parse request data: We can parse query parameters to customize the greeting message using the command name := c.Query("name"). If the name query parameter is present in the request, its value will be stored in the name variable. Otherwise, the name variable will be an empty string.
    func handler(c *fiber.Ctx) error {
        name := c.Query("name")
        message := fmt.Sprintf("Hello, %s!", name)
        return c.SendString(message)
    }
  • Access parsed data: Once we have parsed the name query parameter, we can use it to customize the greeting message.
    func main() {
        app := fiber.New()

        app.Use(logger.New())

        app.Get(`/", handler)

        app.Listen(":3000")
    }

With these steps completed, we have parsed request data to customize the greeting message in our simple web application.

Now, if the user sends a request to the URL http://localhost:3000/?name=John, the response will be Hello, John!. If the name query parameter is not present in the request, the response will be Hello, !.

5: Handling Errors in Your Web Application

In Fiber framework, you can handle errors by using the built-in error handling middleware or by defining your own error handling middleware. Here are the steps you need to follow:

  • Define an error handling middleware: We can define an error handling middleware that returns a custom error message if an error occurs using the command - gofunc errorHandler(c *fiber.Ctx, err error) error.

See in below example

    func errorHandler(c *fiber.Ctx, err error) error {
        return c.SendString("An error occurred: " + err.Error())
    }
  • Register the error handling middleware: We can register the error handling middleware using the command app.Use(errorHandler). The error handling middleware will be executed for every incoming request that results in an error.
    func main() {
        app := fiber.New()

        app.Use(logger.New())
        app.Use(errorHandler)

        app.Get("/", func(c *fiber.Ctx) error {
            if rand.Intn(10) > 5 {
            return fmt.Errorf("random error occurred")
            }
            name := c.Query("name")
            message := fmt.Sprintf("Hello, %s!", name)
            return c.SendString(message)
        })

        app.Listen(":3000")
    }

With these steps completed, we have handled errors in our simple web application. Now, if an error occurs while processing a request, the error handling middleware will return a custom error message. For example, if the user sends a request to the URL http://localhost:3000/?name=John and a random error occurs, the response will be An error occurred: random error occurred.

Creating web applications with Golang and Fiber framework is a simple and straightforward process. By following the steps outlined in this article, you can create a basic web application that handles requests, sends responses, and handles errors.

Hope you liked this article, if you have any questions write down in the comments.