DEV Community

Yosef Seboka
Yosef Seboka

Posted on

1

Middleware in Golang Gin

Middleware is a powerful feature that allows developers to execute code before or after a request is handled by the router. This can be used to perform a variety of tasks such as logging, authentication, and error handling.

In Gin, middleware is defined as a function that takes in a context and a handler, and returns a new handler. The context is an object that holds information about the current request and response, and the handler is the function that will handle the request.

func LoggingMiddleware() gin.HandlerFunc {
    return func(c *gin.Context) {
        log.Println(c.Request.Method, c.Request.URL.Path)
        c.Next()
    }
}

Enter fullscreen mode Exit fullscreen mode

It is also possible to use middleware on specific routes or groups of routes by passing the middleware as an argument to the GET(), POST(), etc. methods. For example:

r.GET("/", LoggingMiddleware(), func(c *gin.Context) {
    c.String(200, "Hello, World!")
})

Enter fullscreen mode Exit fullscreen mode

In this example, the LoggingMiddleware will be executed before the handler function is called.

Gin also provides a built-in middleware for handling errors, called Recovery. It will recover from any panics and logs the panic message. To use this middleware, you can add it to the router using the Use() method:

r := gin.Default()
r.Use(gin.Recovery())
Enter fullscreen mode Exit fullscreen mode

In conclusion, Middleware in Golang Gin is like the superhero sidekick of your web development journey. It's always there to save the day, whether it's logging requests, handling errors, or implementing authentication. With Gin's middleware feature, you can add functionality to your application without having to change the existing routing structure, it's like having a swiss army knife for your web development needs. So don't be shy, give your middleware some love, and watch it make your life as a developer a whole lot easier.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay