How to create API using Fiber in Golang

How to create simple API using golang and express like Fiber package


Golang is a programming language developed by Google. It can used to create cloud services, web , CLI tools etc. The first step to use Go is download and install the SDK.

Basic setup

To build basic API in Golang we need following packages

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

Fiber is express inspired library, if you were familiar with Nodejs express package, no worries . In the main.go file add the following

package main

import  
("github.com/gofiber/fiber/v2"
"fmt"
"log"
)
 
func api(c *fiber.Ctx) error {
    msg := fmt.Sprintf("✋ %s", c.Params("*"))
    return c.SendString(msg) // => ✋ register
}


func index(c *fiber.Ctx) error {
    return c.SendString("I am Fiber") // => ✋ register
}


func main(){
	app:= fiber.New()
    app.Get("/",index )
    app.Get("/api/*",api )
    log.Fatal(app.Listen(":3000"))
}

Here we create a Fiber router instance which can be used to create API route. We also define handler function for the API too.

:= is the short hand in Golang for creating variables

Run the project

By using go run . or go run main.go can execute the program.

Author: Manoj

Developer and a self-learner, love to work with Reactjs, Angular, Node, Python and C#.Net

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.