Build a Lightning-Fast API in Golang: A Step-by-Step Guide

In this blog, you are going to see how to develop the first Golang API. This will be a step-by-step guide for beginners that will help you write your first API. It also contains some exercises for you to make it more interesting. Starting with basic installation to seeing output on the Postman, everything is covered here. You will be using Gin Web framework, which is 40 times faster than Martini( another web framework)

Golang is an open-source programming language supported by Google, which is used by many giant companies like Google, Netflix, Meta, Salesforce, Uber, and many others. This is very popular for developing secure, scalable systems.

Installation

First thing first, make sure your go workspace setup is completed, if not, follow the download and install documentation

Install your editor. I will be using VSCode which is very popular for Golang development, but you can use any editor of your choice. For VS Code you have to install a package Go for Golang support.

Also, install postman as a rest client for sending requests. It’s free of cost. 

What are You Building Today?

You will be creating a service called book serv, which can store books and get books.

So in this blog, you will create an API that will create a new book and get the book back. Our book will have the following attributes: id, name, and author. Let’s take an example of a book. 

id: 1

Name: building data-intensive applications

Author: Martin Kleppmann

Just to keep it a beginner-friendly and to-the-point tutorial, we won’t save our data in the database, instead, we will be using the in-memory slice to store it. In a real-world application, you need to replace the in-memory with a database for data persistence. I will discuss this in the next blog.

First Look of APIs

Post /books  

With this API you will be creating a book and storing it. You will send the same book in the response 

GET /books?id = ?

Get the book by id. So any book with that id will be returned.

GET /books

Get all books present without a filter

Delete /books?id =?

Deleting a particular book by book id.

Check Your Basic Setup

Create a new project in your GOPATH 

cd GOPATH/src
mkdir book-serv && cd book-serv

Create a main.go with this boilerplate code

package main

import “fmt”

func main() {
  fmt.Println(“Hello World”)
}

Run the above code with the following command on the terminal.

go run main.go

Open this book serv in VS code. It will look something like this.

This is to check if your basic setup is done.

Package You Will use

  1. http/net: This is a system-level package that helps you to create HTTP servers and clients  
  2. Gin: Gin is a high-performance HTTP web framework written in Golang. It contains a set of commonly used functionalities (e.g., routing, middleware support, rendering, etc.)

Struct for Book Resource

Let’s see how your Book structs will look like

type Book struct {
  Id     int
  Title  string
  Author string
}

Create a Go Module

As you will use packages like gin, you will need go module for your project.

Follow the steps to initialize go Module and import packages to the local system.

go mod init

After this you can see go.sum in your folder.

Now is the time to import gin web framework. You can simply run this on your terminal.

go get -u github.com/gin-gonic/gin

It will take some time. After this you can see go.mod file in your folder

Time to Code

After doing everything it’s time to code. With the help of gin documentation, run this simplest example. 

package main

import (
  “net/http”

  “github.com/gin-gonic/gin”
)

func main() {
  r := gin.Default()
  r.GET(“/ping”, func(c *gin.Context) {
    c.JSON(http.StatusOK, gin.H{
      “message”: “pong”,
    })
  })
  r.Run() // listen and serve on 0.0.0.0:8080 (for windows “localhost:8080”)
}

It will be like this. You can check the output now on postman

With this, you are able to use gin to serve requests on localhost and 8080 port.

Exercise for you: 

Find how to run this server on port 10000 or any other port.

Now you will start writing code for our initial problem of adding and getting books.

Adding some suffixes in structs for making JSON encoding and decoding. You will write a function that gets all books.

Writing API for getting all books

package main

import (
  “net/http”
  “github.com/gin-gonic/gin”
)

type Book struct {
  Id     int    `json:”bookId”`
  Title  string `json:”Title”`
  Author string `json:”Author”`
}

var books = []Book{
  Book{Id: 1, Title: “Building Data-Intensive Applications”, Author: “Martin Kleppmann”},
  Book{Id: 2, Title: “Refactoring”, Author: “Martin Fowler,”},
  Book{Id: 3, Title: “Cracking the Coding Interview”, Author: “Gayle Laakmann McDowell”},
}

func getAllBooks(c *gin.Context) {
  c.JSON(http.StatusOK, books)
}

func main() {
  r := gin.Default()
  r.GET(“/books”, getAllBooks)
  r.Run()
}

With this, your first API to get all books in done!!!

Book Create API

You can add a handler like this:

r.POST(“/books”, createBooks)

Method will look like this:

func createBooks(c *gin.Context) {
  var newBook Book

  if err := c.BindJSON(&newBook); err != nil {
      return
  }
  books = append(books, newBook)
  c.JSON(http.StatusOK, newBook)
}

This will return the same book in the response. You can also check get all books API to verify.

I will be updating this gist for the other APIs like getting books by id, and deleting books.

Conclusion

Gin is a really powerful web framework in Golang. You have seen some of the capabilities today. This tutorial will help you to write API in Golang from the scratch. This step-wise tutorial can help you to understand the basic concepts of Golang along with examples. After this, you will be able to write your own API in Golang, which will be lighting-Fast.

Happy Coding!!!

This Post Has 6 Comments

  1. Anonymous

    Thanks, this is really helpful!

Leave a Reply