Go (or Golang) has become a popular choice for backend development, thanks to its performance, simplicity, and strong concurrency features. In this tutorial, we’ll build a simple REST API using Go and Gin, a fast and minimalistic web framework.
Prerequisites
Before we start, make sure you have Go installed on your machine (version 1.18 or newer).
Step 1: Setting Up the Project
First, create a new directory for your project and initialize a Go module.
mkdir go-gin-api
cd go-gin-api
go mod init example.com/go-gin-api
Next, let’s add Gin as a dependency.
go get -u github.com/gin-gonic/gin
Step 2: Writing the Code
Create a file named main.go
and add the following code. We’ll create a simple API with a single endpoint that returns a JSON response.
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
// Initialize a Gin router with default middleware
router := gin.Default()
// Define a route for GET /hello
router.GET("/hello", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "Hello, World from Gin!",
})
})
// Run the server on port 8080
router.Run(":8080")
}
What’s happening here?
- We import the necessary packages:
net/http
for status codes andgin
. gin.Default()
creates a router with some helpful middleware, like a logger and a recovery mechanism.- We define a handler for
GET
requests to the/hello
path. - The handler function receives a
gin.Context
, which carries request details and allows us to write a response. c.JSON()
serializes the givengin.H
(a shortcut formap[string]interface{}
) into a JSON response with a200 OK
status code.router.Run(":8080")
starts the HTTP server and makes it listen for requests on port 8080.
Step 3: Running Your API
You can now run your API from the terminal:
go run main.go
You should see output from Gin indicating the server is running. Now, open a new terminal or your web browser and access http://localhost:8080/hello
.
You will receive the following JSON response:
{
"message": "Hello, World from Gin!"
}
Congratulations! You’ve just built and run your first API with Go and Gin. This is just the beginning. From here, you can explore routing parameters, handling different HTTP methods, connecting to a database, and much more.