我为成功投放的路线制作了middleware
但是有一个小问题,它将适用于所有路线,包括signup
和login
。我希望社交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。我搜索谷歌,但我发现我不明白的东西可以帮助我。提前谢谢。
答案 0 :(得分:0)
https://github.com/gin-gonic/gin#using-middleware,展示了如何使用授权中间件的特定网址集。
答案 1 :(得分:0)
来自:https://github.com/gin-gonic/gin#using-middleware
// Per route middleware, you can add as many as you desire.
r.GET("/benchmark", MyBenchLoggerMiddleware(), benchEndpoint)