Skip to content

Instantly share code, notes, and snippets.

@thanhdatvo
Created April 30, 2020 20:51
Show Gist options
  • Save thanhdatvo/a0818824c8f7d84601fd7829c31388fe to your computer and use it in GitHub Desktop.
Save thanhdatvo/a0818824c8f7d84601fd7829c31388fe to your computer and use it in GitHub Desktop.
Go Fiber chained middlewares
func main() {
// initialization codes
app.Get("/verify/:status/:role/:userId", authenticate, authorize, func(c *fiber.Ctx) {
if c.Locals("isAuthenticated") == false {
c.Status(403)
c.Send("Unauthenticated. Please signup!")
return
}
c.Send("Redirecting " + c.Locals("redirectRoute").(string))
})
// some other codes
}
func authenticate(c *fiber.Ctx) {
if c.Params("status") == "authenticated" {
c.Locals("isAuthenticated", true)
} else {
c.Locals("isAuthenticated", false)
}
c.Next()
}
func authorize(c *fiber.Ctx) {
if c.Locals("isAuthenticated") == false {
c.Next()
return
}
if c.Params("role") == "admin" {
c.Locals("redirectRoute", "dashboard")
} else if c.Params("role") == "user" {
c.Locals("redirectRoute", "homepage/"+c.Params("userId"))
} else {
c.Locals("redirectRoute", "contact-support")
}
c.Next()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment