我为路由编写了一个中间件,它成功运行,但存在一个小问题,那就是它将应用于所有路由,包括"signup"和"login"。我希望针对这两个路由开放给所有用户。以下是我正在使用的代码:-
当我访问
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()
}
}
当我访问
/login
链接时,登录API将运行并检查用户是否经过授权。但是中间件代码也将应用于注册和登录。我该如何区分登录API和注册API呢?我在谷歌上搜索了一些东西,但是我不理解,请有人帮助我。提前感谢您的帮助。