How to create an API with Golang and Fiber – Part 02

Routing is an important piece for every web application. Is here that you will map the client’s requests to your server.

To begin our Figo API will have five endpoints, that will be responsible to create, read, update, and delete (CRUD) our expenses.

Since we are implementing using the RESTFul architectural style, our program will heavily rely on the HTTP verbs.

POSTCreate/expenses
GETRead (list)/expenses
GETRead (one)/expenses/{id}
PUTUpdate/expenses/{id}
DELETEDelete/expenses/{id}

In the previous article, we didn’t initialize our repository on Github. So, doing this now.

First, go to your Github account and create your repository with the same naming convention of our project. Mine will be, https://github.com/bootmind/figo

On your terminal initialize Git and sync your remote repo.

git init
git add .
git commit -m "First commit with Fiber setup"
git remote add origin git@github.com:bootmind/figo-api.git
git push -u origin master

One thing that I saw, was our fiber dependency as an //indirect import, and we are using directly, however, Go provides the following command to solve that out.

go mod tidy

This command will also remove unused packages, so keep that in mind.

Great, now we have our project versioned. Moving forward, on your machine in the project’s root path, create a folder called “pkg”.

In here /pkg, we will be creating three folders.

  • entity
  • handler
  • route

The entity will hold our model structure.

The handler will act as a controller.

The route as you would expect will be responsible for the methods and paths matching the HTTP request.

Create the file /pkg/entity/expense.go

package entity

import "time"

// Expense type
type Expense struct {
	ID         string    `json:"id"`
	Title      string    `json:"title"`
	Total      float64   `json:"total"`
	Attachment string    `json:"attachment"`
	CreatedAt  time.Time `json:"createdAt"`
}

We are typing the attributes and also setting the JSON format of our model.

Create the file /pkg/handler/expenses.go

package handler

import (
	"time"

	"github.com/bootmind/figo/pkg/entity"
	"github.com/gofiber/fiber/v2"
)

// ExpenseHandler type
type ExpenseHandler struct {
}

// Index to list all expenses
func (h ExpenseHandler) Index(ctx *fiber.Ctx) error {
	expenses := []entity.Expense{
		{
			ID:         "1",
			Title:      "Lunch at MyFood",
			Total:      14.95,
			Attachment: "photo.jpg",
			CreatedAt:  time.Now(),
		},
	}
	return ctx.JSON(fiber.Map{"data": expenses})
}

We have a struct, empty for now, and our Index function, which will interact with the client request. Create the file /pkg/route/expenses.go

package route

import (
	"github.com/bootmind/figo/pkg/handler"
	"github.com/gofiber/fiber/v2"
)

// Expenses route
func Expenses(app *fiber.App) {
	var h handler.ExpenseHandler
	r := app.Group("/expenses")
	r.Get("/", h.Index)
}

Mapping our available routes for our /expenses endpoint.

Last, but not least we will update our main file.

package main

import (
	"github.com/bootmind/figo/pkg/route"
	"github.com/gofiber/fiber/v2"
)

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

	app.Get("/", func(c *fiber.Ctx) error {
		return c.JSON(map[string]string{
			"message": "Figo API",
		})
	})

	route.Expenses(app)
	app.Listen(":3000")
}

We configure our expense route on line 17.

Now, run the application again and go to http://localhost:3000/expenses. You should see the following response.

{
  "data": [
    {
      "id": "1",
      "title": "Lunch at MyFood",
      "total": 14.95,
      "attachment": "photo.jpg",
      "createdAt": "2020-09-29T20:51:52.229956629+01:00"
    }
  ]
}

Github repository: https://github.com/bootmind/figo-api

Part 01 https://blog.bootmind.com/golang/how-to-create-an-api-with-golang-and-fiber-part-01/

Part 03 https://blog.bootmind.com/golang/how-to-create-an-api-with-golang-and-fiber-part-03/

Part 04 https://blog.bootmind.com/golang/how-to-create-an-api-with-golang-and-fiber-part-04/

Part 05 https://blog.bootmind.com/golang/how-to-create-an-api-with-golang-and-fiber-part-05/


Posted

in

,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.