codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🐹

Go (Golang)

44 / 72 topics
42Third-Party Libraries Overview43GORM (Object-Relational Mapping)44Gin Framework45Echo Framework46Cobra CLI Library47Viper Config Library48Go Bindata for Embedding Assets49gRPC (Remote Procedure Calls)50Protocol Buffers
Tutorials/Go (Golang)/Gin Framework
🐹Go (Golang)

Gin Framework

Updated 2026-04-20
3 min read

Introduction to Gin Framework

The Gin Framework is a high-performance HTTP web framework written in Go (Golang). It is known for its speed, efficiency, and simplicity. Gin provides a robust set of features that make it an excellent choice for building web applications, APIs, and microservices.

In this tutorial, we will explore the basics of using the Gin Framework to create a simple web server. We'll cover setting up the environment, creating routes, handling requests, and integrating middleware.

Setting Up Your Environment

Before you start, ensure that you have Go installed on your system. You can download it from the official website: golang.org.

Once Go is installed, create a new directory for your project and initialize a new module:

mkdir gin-tutorial
cd gin-tutorial
go mod init gin-tutorial

Next, install the Gin Framework by running:

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

Creating Your First Gin Application

Let's start by creating a simple web server using Gin. Create a new file named main.go and add the following code:

package main

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

func main() {
    // Initialize the Gin router
    r := gin.Default()

    // Define a route for the root URL
    r.GET("/", func(c *gin.Context) {
        c.JSON(200, gin.H{
            "message": "Hello, Gin!",
        })
    })

    // Start the server on port 8080
    r.Run(":8080")
}

Explanation

  1. Importing Packages: We import the github.com/gin-gonic/gin package to use the Gin Framework.
  2. Initializing the Router: gin.Default() initializes a Gin router with default middleware (logger and recovery).
  3. Defining Routes: We define a route for the root URL (/) that responds with a JSON object containing a message.
  4. Starting the Server: r.Run(":8080") starts the server on port 8080.

Running Your Application

To run your application, execute the following command in your terminal:

go run main.go

Open your web browser and navigate to http://localhost:8080. You should see a JSON response with the message "Hello, Gin!".

Handling Different HTTP Methods

Gin supports all standard HTTP methods such as GET, POST, PUT, DELETE, etc. Let's add routes for each of these methods:

package main

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

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

    // GET method
    r.GET("/get", func(c *gin.Context) {
        c.JSON(200, gin.H{
            "method": "GET",
        })
    })

    // POST method
    r.POST("/post", func(c *gin.Context) {
        c.JSON(200, gin.H{
            "method": "POST",
        })
    })

    // PUT method
    r.PUT("/put", func(c *gin.Context) {
        c.JSON(200, gin.H{
            "method": "PUT",
        })
    })

    // DELETE method
    r.DELETE("/delete", func(c *gin.Context) {
        c.JSON(200, gin.H{
            "method": "DELETE",
        })
    })

    r.Run(":8080")
}

Testing the Routes

You can test these routes using tools like curl or Postman. For example, to test the POST route:

curl -X POST http://localhost:8080/post

This should return a JSON response with the method type.

Handling Parameters and Query Strings

Gin allows you to handle URL parameters and query strings easily. Here's an example of how to do this:

package main

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

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

    // Route with a parameter
    r.GET("/user/:name", func(c *gin.Context) {
        name := c.Param("name")
        c.JSON(200, gin.H{
            "username": name,
        })
    })

    // Route with query parameters
    r.GET("/search", func(c *gin.Context) {
        query := c.Query("q")
        c.JSON(200, gin.H{
            "query": query,
        })
    })

    r.Run(":8080")
}

Testing the Parameters

To test the parameter route:

curl http://localhost:8080/user/john

This should return a JSON response with the username.

For the query string route:

curl "http://localhost:8080/search?q=example"

This should return a JSON response with the query parameter.

Middleware in Gin

Middleware functions are executed before the request handler. They can be used for tasks like authentication, logging, and more. Here's an example of how to create and use middleware:

package main

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

func authMiddleware() gin.HandlerFunc {
    return func(c *gin.Context) {
        // Simulate a user check
        if c.GetHeader("Authorization") != "Bearer valid-token" {
            c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
            c.Abort()
            return
        }
        c.Next()
    }
}

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

    // Apply the middleware globally
    r.Use(authMiddleware())

    r.GET("/protected", func(c *gin.Context) {
        c.JSON(200, gin.H{
            "message": "This is a protected route",
        })
    })

    r.Run(":8080")
}

Explanation

  1. Creating Middleware: The authMiddleware function checks for an authorization header and returns a 401 Unauthorized response if it's missing or invalid.
  2. Applying Middleware: We apply the middleware globally using r.Use(authMiddleware()). This means that all routes will require authentication.

Testing the Middleware

To test the protected route with valid and invalid tokens:

curl -H "Authorization: Bearer valid-token" http://localhost:8080/protected

This should return a JSON response with the message.

curl http://localhost:8080/protected

This should return a 401 Unauthorized response.

Conclusion

In this tutorial, we covered the basics of using the Gin Framework to create a simple web server. We learned how to set up routes, handle different HTTP methods, work with parameters and query strings, and use middleware for authentication and other tasks. Gin's simplicity and performance make it an excellent choice for building efficient web applications in Go.

Feel free to explore more advanced features of Gin, such as form binding, file uploads, and custom middleware, to further enhance your applications.


PreviousGORM (Object-Relational Mapping)Next Echo Framework

Recommended Gear

GORM (Object-Relational Mapping)Echo Framework