Skip to content

Instantly share code, notes, and snippets.

@dakait
Created August 29, 2018 12:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dakait/1c38d2dab77d965030a072ba660463b0 to your computer and use it in GitHub Desktop.
Save dakait/1c38d2dab77d965030a072ba660463b0 to your computer and use it in GitHub Desktop.
Chaining handler functions with gin
//Golang doesn't have python-Django like decorators but here is
//a small example of what you can do
package main
import "github.com/gin-gonic/gin"
func Handler(h gin.HandlerFunc, decors ...func(gin.HandlerFunc)gin.HandlerFunc) gin.HandlerFunc {
for i := range decors {
d := decors[len(decors) - 1 - i] // iterate in reverse
h = d(h)
}
return h
}
func isSuperUser (handlerFunc gin.HandlerFunc) gin.HandlerFunc {
return func (context *gin.Context) {
// assuming you already have user through middleware
if user.IsAdmin {
handlerFunc(context)
} else {
context.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"status":"you are not authorized"})
}
}
}
func main() {
router := gin.Default()
router.GET("/welcome", Handler(welcome, isSuperUser))
}
func welcome(context *gin.Context) {
context.JSON(200, gin.H{"status": "ok"})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment