2. Handling HTTP Requests with Gin – Gin Middleware

2.8 Gin Middleware

2.8.1 What is Gin Middleware

    In Gin, middleware is a way to add common functionality to HTTP handlers. In the context of Gin, middleware refers to a set of functions or handlers that are executed during the HTTP request and response lifecycle.

Gin middleware can be used for various purposes, such as logging, authentication, rate limiting, error handling, and more. Developers can create custom middleware or use existing middleware provided by the Gin community. Its features are as follows:

  • Modularity: Middleware can be added, removed, or modified without affecting the core functionality of the existing program
  • Reusability: Middleware can be used across multiple programs and routes
  • Chaining: Allows multiple middleware to be called in a specific order to handle requests
  • Interoperability: Middleware can be compatible with other middleware and third-party libraries used in the program
  • Context Awareness: Middleware can access and modify request and response objects, as well as other relevant context information
  • Error Handling Mechanism: Middleware can ensure that errors are handled correctly, preventing unexpected behavior in the program

    Key components of Gin middleware include:

  • Function Signature: A function that receives a <span>*gin.Context</span> object
  • Return Value: Returns a “gin.HandlerFunc“, which is the type that Gin middleware functions must satisfy
  • Middleware Logic: Executes any necessary operations within the middleware function, such as logging, authentication, request validation, or modifying requests and responses

2.8.2 Using Middleware

    To use middleware in Gin, you can use the <span>User()</span> method, as shown in the example code below:

package main

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

// Custom middleware
func Logger() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		t := time.Now()
		time.Sleep(3 * time.Second)
		ctx.Set("name", "Surpass")
		// Before request
		ctx.Next()
		// After request
		log.Printf("耗时:%v,状态:%v\n", time.Since(t), ctx.Writer.Status())
	}
}

func main() {
	r := gin.Default()
	r.Use(Logger())
	r.GET("/middleware-test", func(ctx *gin.Context) {
		log.Println("测试中间件")
	})
	r.Run()
}

Leave a Comment