Gin is a web framework for Golang which makes building web applications easier and faster. It is a lightweight framework that provides support to create RESTful APIs and web applications. In this blog, we'll dive into the Gin library, explore its key features and provide code snippets to help you get started.
Installing Gin
Before we dive into Gin, we need to install it. You can install Gin using the go get
command:
go get -u github.com/gin-gonic/gin
This command will download and install Gin and its dependencies.
Creating a Basic Gin Server
Now that we have Gin installed, let's create a basic Gin server. Create a new file named main.go
and add the following code:
package main
import "github.com/gin-gonic/gin"
func main() {
r := gin.Default()
r.GET("/", func(c *gin.Context) {
c.JSON(200, gin.H{
"response": "I tested my first program using gin framework",
})
})
r.Run()
}
This code creates a new Gin server, defines a route for the root URL and starts the server. The gin.Default()
function creates a Gin engine with the logger and recovery middleware already attached. We define a GET route for the root URL using the r.GET
method. Inside the route handler, we use the c.JSON
method to return a JSON response.
Handling Path parameters
Gin allows you to define path parameters which are dynamic values in the URL. Path parameters are defined by placing a colon :
before the parameter name in the route definition. For example, the route /users/:id
defines a route parameter named id
.
r.GET("/blog/:id", func(c *gin.Context) {
id := c.Param("id")
c.JSON(200, gin.H{
"response": fmt.Sprintf("Blog %s", id),
})
})
In this code, we define a route for /blog/:id
. Inside the route handler, we use the c.Param
method to get the value of the id
parameter.
Handling Query Parameters
Gin also allows you to handle query parameters which are key-value pairs in the URL. Query parameters are accessed using the c.Query
method.
r.GET("/blog", func(c *gin.Context) {
title := c.Query("title")
section := c.Query("section")
c.JSON(200, gin.H{
"title": title,
"section": section,
})
})
In this code, we define a route for /blog
. Inside the route handler, we use the c.Query
method to get the values of the title
and section
query parameters. And then we send back the same value in response. You can run and check it by making curl request.
Handling POST Requests
Gin allows you to handle POST requests using the r.POST
method.
type Blog struct {
Title string `json:"title"`
Section string `json:"section"`
}
r.POST("/blog", func(c *gin.Context) {
var blog Blog
err := c.ShouldBindJSON(&blog)
if err != nil {
errResponse:= gin.H{"error": err.Error()}
c.AbortWithStatusJSON(http.StatusBadRequest,errResponse)
return
}
response:= fmt.Sprintf("Blog created with title as %s", blog.Title)
c.JSON(200, gin.H{
"response": response,
})
})
In this code, we define a route for POST requests to /blog
. Inside the route handler, we use the c.ShouldBindJSON
method to parse JSON request body and bind it to struct Blog
. If there is an error parsing the JSON data, we return a JSON response with an error message and a http.StatusBadRequest
status code. If the parsing is successful we give back the response as success.
Testing in your machine:
Full code can be found here: Github link
Steps to run:
Clone the above file and install dependencies.
Start the Golang server using the command
go run .
You can use
curl
to test it.Make GET call to test get endpoint
curl -v
http://localhost:8080/
Make POST call to test post endpoint.
curl -v
http://localhost:8080/blog
--request POST --data '{"title":"first_blog","section":"sample section"}'
Hurray😃!! We learned about golang gin framework, now go ahead and use it.