Getting Started | Developing an API with Go and Gin
Writing first go-based REST API.
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 a 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.
- A IDE to edit your code.
- A command terminal.
Creating Go Project
- Create a folder for our project
mkdir go-gin-api
cd go-gin-api
- 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.
- 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
- Begin tracking the Gin module as a dependency. To retrieve all the required dependencies in the current folder run the below command.
go get .
- Now run the main file using the below command
go run main.go
or
go run .
- After this, our application will be executed and an API will be exposed.
Now go to your favorite browser and hit 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