Article

Table of Contents
Theme:
Was this article helpful?

2  out of  2 found this helpful

Try Vultr Today with

$50 Free on Us!

Want to contribute?

You could earn up to $600 by adding new articles!

How to Set Up a Fiber Server with Golang on Ubuntu 21.04

Author: Nabeel Ahmed

Last Updated: Thu, Sep 16, 2021
Golang Ubuntu Web Servers

Overview

Fiber is a web framework written in Golang. It features an efficient HTTP engine, a growing middleware community, and an easy-to-use Express-inspired API. This guide explains how to install Fiber and perform some basic tasks on Ubuntu 21.04.

Prerequisites

Install Golang

Fiber requires Golang 1.14 or greater and build-essential.

  1. Install build-essential.

    $ sudo apt install build-essential
    
  2. Locate the latest stable linux-amd64 Golang version on the official site.

  3. Download the latest stable version. Your filename may be different than shown.

    $ wget https://golang.org/dl/go1.17.linux-amd64.tar.gz
    
  4. Extract the compressed build file to the local binaries folder.

    $ sudo tar -C /usr/local -xvzf go1.17.linux-amd64.tar.gz
    
  5. Add the Golang build to the PATH environment variable.

    $ echo "export PATH=$PATH:/usr/local/go/bin" >> ~/.profile
    
  6. Reload your profile.

    $ source ~/.profile
    
  7. Verify the Golang installation.

    $ go version
    go version go1.17 linux/amd64
    

Initialize the Project

  1. Create the project root directory.

    $ cd ~
    $ mkdir fiberserver && cd fiberserver
    
  2. Initialize the Golang project environment.

    Replace example.com with a unique URL that corresponds with your project's remote location. For most projects, this may be github.com if your code is hosted there. If your code is on a custom remote location, use the URL of that location. If you do not make your project downloadable, replace example.com with any unique text identifier.

    $ go mod init example.com/fiberserver
    
  3. Install Fiber.

    $ go get github.com/gofiber/fiber/v2
    
  4. Create a main Golang file in the project root.

    $ nano main.go
    
  5. Paste the following code into the main.go file.

    The code starts a web server on port 3000 and returns "Hello, World!" to any requests sent to the / endpoint.

    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!\n")
            })
    
            app.Listen(":3000")
    }
    

Fiber can listen on the standard HTTP port by changing app.Listen(":3000") to app.Listen(":80"). Keep in mind that non-root users cannot bind processes to ports below 1024. You should use a proxy server such as Nginx in front of Fiber for production use.

Compile and Run the Server

  1. Change to the project folder.

    $ cd ~/fiberserver
    
  2. Compile the project code.

    $ go build
    
  3. Run the compiled binary file.

    $ ./fiberserver
    
  4. Navigate to your server's IP address at port 3000 in a web browser. For example:

    http://192.0.2.123:3000      
    

You should see the "Hello, World!" page.

Add Routes

Fiber is easy to expand with the app.Group API. Here is how to create a basic route organized in its own package.

  1. Change to the project folder.

    $ cd ~/fiberserver
    
  2. Create a new route folder.

    $ mkdir api
    
  3. Change to the new folder and create a new Golang file.

    $ cd api
    $ nano api.go
    
  4. Paste the following to add the hello route under the /api group.

    package api
    
    import (
            "github.com/gofiber/fiber/v2"
    )
    
    func Route(app *fiber.App) {
        api := app.Group("/api")
    
        api.Get("/hello", func (c *fiber.Ctx) error {
            return c.SendString("Hello from API!\n")
        })
    }
    

    For consistency, keep the package name the same as the route folder name.

  5. Return to the project root and replace the code in main.go to the following to implement the new route.

    package main
    
    import (
            "example.com/fiberserver/api"
            "github.com/gofiber/fiber/v2"
    )
    
    func main() {
            app := fiber.New()
    
            app.Get("/", func (c *fiber.Ctx) error {
                    return c.SendString("Hello, World!\n")
            })
    
            api.Route(app) // add new route
    
            app.Listen(":3000")
    }
    

    Remember to change the example.com in example.com/fiberserver/api to the module name you chose when the project was initialized. If you called the project folder something else, change fiberserver to that name. Also, api at the end of the statement is the name of the folder you created for the new route.

  6. Re-compile the project.

    $ go build
    
  7. Run the new binary.

    $ ./fiberserver
    
  8. Navigate to your server's IP address at port 3000 in a web browser. For example:

    http://192.0.2.123:3000      
    

    You should see the "Hello, World!" page.

  9. Test the new route:

    http://192.0.2.123:3000/api/hello      
    

    This time, you should see the "Hello from API!" page.

Add Middleware

Use the app.Use API to add middleware. Follow the steps below to set up a simple middleware that overrides user requests depending on their client.

  1. Edit the main.go file and replace the code with the following. The following middleware checks if the client is using Linux through the User-Agent request header and overrides every request with a message.

    package main
    
    import (
            "strings"
    
            "example.com/fiberserver/api"
            "github.com/gofiber/fiber/v2"
    )
    
    func main() {
            app := fiber.New()
    
            // Check if client is using Linux
            app.Use(func (c *fiber.Ctx) error {
                if strings.Contains(c.Get("User-Agent"), "Linux x86_64") {
                    return c.SendString("You are using a Linux client.\n")
                }
                return c.Next()
            })
    
            app.Get("/", func (c *fiber.Ctx) error {
                    return c.SendString("Hello, World!\n")
            })
    
            api.Route(app) // add new route
    
            app.Listen(":3000")
    }
    
  2. While in the root of the project folder, re-compile the project code.

    $ go build
    
  3. Execute the new compiled binary.

    $ ./fiberserver
    
  4. Navigate to your server's IP address at port 3000 in a web browser. For example:

    http://192.0.2.123:3000      
    

If you use Linux, you should see "You are using a Linux client.", otherwise you see "Hello, World!"

Create a Service

Register a service to restart Fiber when the server restarts automatically.

  1. Compile the project.

    $ cd ~/fiberserver
    $ go build
    
  2. Create a fiberserver.service file in /lib/systemd/system/.

    $ sudo nano /lib/systemd/system/fiberserver.service
    
  3. Paste the following to the file. Replace the ExecStart path with the location of the compiled project code.

    [Unit]
    Description=Fiber Server
    
    [Service]
    Type=simple
    Restart=always
    RestartSec=10s
    ExecStart=/path/to/compiled/binary/file
    
    [Install]
    WantedBy=multi-user.target
    
  4. Enable the service to allow it to start on boot automatically.

    $ sudo systemctl enable fiberserver
    
  5. Start the service.

    $ sudo systemctl start fiberserver
    
  6. Reboot the server.

    $ reboot
    
  7. Wait for the server to reboot, then navigate to your server's IP address at port 3000 in a web browser. For example:

    http://192.0.2.123:3000      
    

    You should see a working server response.

More Information

For more information, please see the Fiber documentation.

Want to contribute?

You could earn up to $600 by adding new articles