Custom middleware

As we mentioned earlier, Gin allows you to author your own middleware so that you can embed some functionality in your web app. Writing custom middleware in Gin is relatively simple, as we can see in the following steps.

The first step is to write the actual code for the middleware.

As we mentioned earlier, a web API middleware is simply an HTTP handler function that encapsulates other HTTP handler functions. Here is what the code would look like for this:

func MyCustomMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
//The code that is to be executed before our request gets handled, starts here

// Set example variable
c.Set("v", "123")
//We can then retrieve the variable later via c.Get("v")

// Now we our request gets handled
c.Next()

// This code gets executed after the handler gets handled

// Access the status we are sending
status := c.Writer.Status()
// Do something with the status
}
}

Let's write a very simple middleware that would print ************************************ before and after the request:

func MyCustomLogger() gin.HandlerFunc {
return func(c *gin.Context) {
fmt.Println("************************************")
c.Next()
fmt.Println("************************************")
}
}

The next step is to add this middleware to our Gin engine. This can be done in two ways:

  • If we want to keep Gin's default middleware, but then add MyCustomLogger(), we can do the following:
func RunAPIWithHandler(address string, h HandlerInterface) error {
//Get gin's default engine
r := gin.Default()
r.Use(MyCustomLogger())
/*
The rest of our code
*/
}
  • If, on the other hand, we want to ignore Gin's default middleware and only enable our custom middleware, we can use the following code path:
r := gin.New()
r.Use(MyCustomLogger())

If we'd like to enable more than one middleware, we just add them as an argument to the Use() method, as follows:

 r := gin.New()
r.Use(MyCustomLogger1(),MyCustomLogger2(),MyCustomLogger3())

In the next section, we'll discuss how to secure our web application.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.135.80