Getting Started | Developing an API with Go and Gin



Hello Friends, Today we will understand and write our Go REST API from scratch. We will go through the pre-requisites and later will write the code.

Tip : If you are new to Go, Please visit this link to have better understanding of Go.

The requirement for running our first RestFul API with GO.

For executing any GO program, the following steps must be followed.

  • An installation of Go. For installation instructions, see Installing Go.
  • An IDE to edit your code. 
  • A command terminal. 

Creating Go Project

  1. Create a folder for our project
mkdir go-gin-api
cd go-gin-api

2. Create a module file for dependencies. Run the go mod init command, giving it the path of the module your code will be in.

go mod init example/go-gin-api

This command creates a go.mod file in which dependencies you add will be listed for tracking.

3. create main.go and add the below code and save the file.

package main
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
 fmt.Println("Starting main execution")
router := gin.Default()
router.GET("/", getResponse)
router.Run("localhost:8080")
}
func getResponse(c *gin.Context) {
//write your logic for the api
c.IndentedJSON(http.StatusOK, "Hello from go-gin")
}


Running the Go Project


  1. Begin tracking the Gin module as a dependency to retrieve all the required dependencies in the current folder. Run the below command.
go get .

2. Now run the main file using the below command

go run main.go
or 
go run .

3. After this our application will be executed and an API will be exposed.

Now go to your favorite browser and hit http://localhost:8080 and you will get the below response.


Thanks for reading. I hope this story was helpful. If you are interested,

check out my other articles.

you can also visit shubhamdeshmukh.com.

GitHub: https://github.com/sd2995/GoLang/tree/main/go-gin-api



 

Comments

Popular posts from this blog

Loki, Grafana, and Promtail integration using Docker

Getting Started | Infrastructure as Code(IaC) with examples.

Monitoring multiple federated instances with Prometheus