Created
April 30, 2020 20:51
-
-
Save thanhdatvo/a0818824c8f7d84601fd7829c31388fe to your computer and use it in GitHub Desktop.
Go Fiber chained middlewares
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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