Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

express middleware for specific route using gin package in golang?

Tags:

go

I made a middleware for the routes it successfully runs but there is a small issue that is it will apply for the all the routes include signup and login. I want to social the signupand login route that all users will access these two routes. Below is the code that I am using:-

Routes.go

/*Signup Route */
Route{"SaveUser", "POST", "/signup", controller.SaveUser},

/*Login Route*/
Route{"LoginUser", "POST", "/login", controller.Login},

/* All Customers Routes */
Route{"SaveCustomers", "POST", "/customer", controller.SaveCustomers},
Route{"GetCustomers", "GET", "/customer", controller.GetCustomers},
Route{"GetCustomer", "GET", "/customer/:id", controller.GetCustomer},
Route{"UpdateCustomers", "PUT", "/customer/:id", controller.UpdateCustomers},

func NewRouter() {
  router := gin.Default()
  router.Use(require("./login"))
  router.Use(JWTAuthMiddleware())
  v1 := router.Group("/api/v1")
  for _, route := range routes {
    switch route.Method {
    case "GET":
        v1.GET(route.Pattern, route.HandlerFunc)
    case "POST":
        v1.POST(route.Pattern, route.HandlerFunc)
    case "PUT":
        v1.PUT(route.Pattern, route.HandlerFunc)
    case "DELETE":
        v1.DELETE(route.Pattern, route.HandlerFunc)
    default:
        v1.GET(route.Pattern, func(c *gin.Context) {
            c.JSON(200, gin.H{
                "result": "Specify a valid http method with this route.",
            })
        })
    }
 }
 router.Run(":8080")
}

func JWTAuthMiddleware() gin.HandlerFunc {
  return func(c *gin.Context) {
    controller.ValidateToken(c)
    c.Next()
  }
}

When I hit the url /login then the login API will run and it check whether the user is authorized or not. but the middleware code will is also apply on signup and login. How I will social the login api and the signup api. I searched it for google but the stuff I found i don't understand can anyone help me. Thank you in advance.


1 Answers

From: https://github.com/gin-gonic/gin#using-middleware

// Per route middleware, you can add as many as you desire.
r.GET("/benchmark", MyBenchLoggerMiddleware(), benchEndpoint)
like image 130
HadiAlqattan Avatar answered Sep 23 '25 00:09

HadiAlqattan