Parse query string in Gin web application

0
7317
Parse query string in Gin web application
Parse query string in Gin web application

In this tutorial, I will show you how to parse query string in Gin web application.

Create a Gin project

First, let’s initialize a Gin project so we can go in the same page.

$ mkdir gin-parse-querystring

$ cd gin-parse-querystring

$ go mod init petehouston.com/gin-parse-querystring

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

$ touch main.go

We start with the very basic code for main.go:

package main

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

func main() {
	router := gin.Default()
	router.GET("/", func(c *gin.Context) {
		c.String(http.StatusOK, "blog.petehouston.com - Parse query string in Gin")
	})
	router.Run()
}

Parse query string parameters

To parse query string parameters in Gin-gonic, we will use the context.Query() method, which has following definition:

func (c *Context) Query(key string) (value string)

Let say, there is a request with this query string: /?name=John&age=40&isHired=true, we will parse query params like this:

router.GET("/", func(c *gin.Context) {
	name := c.Query("name")
	age := c.Query("age")
	isHired := c.Query("isHired")

	c.String(http.StatusOK, "Name: %s | Age: %s | isHired: %s", name, age, isHired)
})

You might want to pay attention, the value returns from context.Query() is a string; therefore, you need to convert them into appropriate types for the use cases.

If the value doesn’t exist or value is empty, the query param value will be an empty string. That explains when this request /?name=John&age= comes, the output will become like so:

Missing or empty query parameters
Missing or empty query parameters

Default query parameter value

In such cases, you might want to assign default value to a query parameter if it is missing, you can use context.DefaultQuery() method:

func (c *Context) DefaultQuery(key, defaultValue string) string

We can use it like so:

router.GET("/", func(c *gin.Context) {
	name := c.Query("name")
	age := c.DefaultQuery("age", "40")
	isHired := c.DefaultQuery("isHired", "false")

	c.String(http.StatusOK, "Name: %s | Age: %s | isHired: %s", name, age, isHired)
})

This is how it looks:

Default value if query parameter is missing
Default value if query parameter is missing

You might notice that age parameter value is empty, it is because it is not missing, the value is presented as "" , an empty string. In this situation, you will need to manually check the value and assign it to appropriate one.

Bind query string into structure

Another way to parse query string is to bind them into a data structure. We first need to define the struct for the query string:

type PersonParams struct {
	Name    string `form:"name"`
	Age     int    `form:"age"`
	IsHired bool   `form:"isHired"`
}

Be aware of the syntax form:"KEY" , it must be defined to determine which key to parse from the query string.

Then in the route handler, we can parse the query string into a structure using context.Bind() method:

router.GET("/bind", func(c *gin.Context) {
	var params PersonParams

	if c.Bind(&params) == nil {
		c.String(http.StatusOK, "Name: %s | Age: %d | isHired: %t", params.Name, params.Age, params.IsHired)
	}
})

This is how it looks in browser:

Bind query string into structure
Bind query string into structure

As you can see, by using the context.Bind() we can save more time because it parses query params into the appropriate data type declared in the structure definition. It’s much cooler, right?

Conclusion

Congratulation! Now you know how to parse query string in Gin web application.

Have fun!