Created
August 29, 2018 12:02
-
-
Save dakait/1c38d2dab77d965030a072ba660463b0 to your computer and use it in GitHub Desktop.
Chaining handler functions with gin
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
//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