Skip to content

Gin Web Framework in Go

High-performance HTTP routing, URL parameter extraction, and JSON binding using Gin.

Key Concepts

  • gin.Default(): Initializes the engine with Logger and Recovery middleware.
  • c.Param("name"): Extracts path parameters (/greet/:name).
  • c.ShouldBindJSON(&req): Automatically decodes JSON and validates request bodies.
// Fundamentals learning: Spawning an HTTP Server using Gin (Go's FastAPI equivalent).
// To run: go run basics_learning/2_gin_http/main.go
// Then test using curl:
// GET:  curl http://localhost:8080/greet/Ankush
// POST: curl -X POST http://localhost:8080/submit -H "Content-Type: application/json" -d '{"username": "ankush", "age": 25}'

package main

import (
    "log"
    "net/http"

    "github.com/gin-gonic/gin"
)

// FastAPI:
// class UserRequest(BaseModel):
//     username: str
//     age: int
//
// In Gin, we use struct tags (`json` and `binding`) to define validation and serialization.
type UserRequest struct {
    Username string `json:"username" binding:"required"` // "binding:required" behaves like a required Pydantic field
    Age      int    `json:"age" binding:"required,gte=18"` // Must be at least 18 (greater-than-or-equal)
}

func main() {
    // 1. Initialize Gin Engine
    // gin.Default() automatically sets up recovery (prevents panic crashes) and logging middlewares
    r := gin.Default()

    // 2. GET Route with a Path Parameter
    // FastAPI: @app.get("/greet/{name}")
    // Gin: "/greet/:name"
    r.GET("/greet/:name", func(c *gin.Context) {
        // Retrieve path parameter
        name := c.Param("name")

        // c.JSON(status, payload) automatically handles serialization and sets Content-Type header
        // gin.H is a shortcut map helper: map[string]interface{}
        c.JSON(http.StatusOK, gin.H{
            "message": "Hello, " + name + "!",
        })
    })

    // 3. POST Route with JSON Request Binding
    r.POST("/submit", func(c *gin.Context) {
        var req UserRequest

        // ShouldBindJSON binds the request body (JSON) to our Go struct.
        // If binding fails (e.g. missing required field, age < 18, bad JSON), it returns an error.
        if err := c.ShouldBindJSON(&req); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{
                "error":   "Validation failed",
                "details": err.Error(),
            })
            return
        }

        // Success response
        c.JSON(http.StatusCreated, gin.H{
            "status":   "User registered successfully",
            "username": req.Username,
            "age":      req.Age,
        })
    })

    log.Println("Starting Gin server on :8080...")

    // 4. Start the Gin Engine
    // This is Gin's helper wrapper around http.ListenAndServe.
    if err := r.Run(":8080"); err != nil {
        log.Fatalf("Gin server failed: %v", err)
    }
}