Gin
02 / 02

Gin Fundamentals: Routes, Context & Binding

Gin: Routes, Context & Binding

Gin is a fast, minimalist web framework for building HTTP APIs in Go, built on top of net/http with a radix-tree router designed for low overhead per request.

Basic Routing

func main() {
    router := gin.Default()

    router.GET("/users/:id", func(c *gin.Context) {
        id := c.Param("id")
        c.JSON(200, gin.H{"id": id, "name": "Ada"})
    })

    router.Run(":8080")
}

Binding & Validation

type CreateUserInput struct {
    Name string `json:"name" binding:"required"`
    Age  int    `json:"age" binding:"gte=0"`
}

router.POST("/users", func(c *gin.Context) {
    var input CreateUserInput
    if err := c.ShouldBindJSON(&input); err != nil {
        c.JSON(400, gin.H{"error": err.Error()})
        return
    }
    c.JSON(201, input)
})

Route Groups

api := router.Group("/api/v1")
api.Use(authMiddleware())
{
    api.GET("/profile", getProfile)
    api.PUT("/profile", updateProfile)
}

// Shared prefix + shared middleware for a related set of routes

Keep your own version of these notes — editable, searchable, and organised by your stack.

Start free