---
# System prepended metadata

title: gin with middleware setup
tags: [' middleware', ' gin', golang]

---

---
tags: golang, gin, middleware
---
# gin with middleware setup

## introduction

This is article of how to setup middleware in gin

## usage

Middleware is use do the logic that will spread between some router something like logger, format checker

## middleware function

```golang==
func Logger() gin.HandlerFunc {
	return func(c *gin.Context) {
		t := time.Now()

		c.Set("middle", "Logger")
		// before router
		c.Next()
		// after router
		latency := time.Since(t)
		log.Print(latency)

		status := c.Writer.Status()
		log.Println("Status:", status)
	}
}

```

## gin setup the middle with gin router

```golang

func SetupRouter() *gin.Engine {
	initRouter := gin.Default()
	initRouter.Use(md.Logger())
	// get router
	initRouter.GET("/", func(context *gin.Context) {
		// context.String(http.StatusOK, "hello gin")
		middle := context.MustGet("middle").(string)
		context.JSON(http.StatusOK, gin.H{
			"message": "hello gin",
			"middle":  middle,
		})
	})
	return initRouter
}

```

## this middleware function will be called for each route of this router