HTTP GET Query Parameters

HTTP GET Query Parameters

Here is how to use query string parameters in Gin.

Any HTTP query parameter like http://localhost:8080/greet?name=Jhon can be extracted with

variable := c.Query("name") // Jhon

Full Example

router.GET("/greet", func(c *gin.Context) {

    name := c.Query("name")

    // checks manually if query parameter is present
    if name == "" {
        name = "Guest"
    }

    c.JSON(http.StatusOK, gin.H{
        "message": "Hello, " + name + "!",
    })
})

Automatically assign a value to missing query parameters.

We manually checked and assigned a value by check if the query parameters string was empty.

With DefaultQuery("param", "Default Value") We can assign a default value for the query parameter if there isn’t one.

name := c.DefaultQuery("name", "Guest")
Last updated on