I am learning to use middleware with the gin framework, but I encountered a problem
I want my test function
to only show up in postman if it meets the requirements of my func tokenauthmiddleware
But my test function is called regardless of whether my body is filled in or not (with or without authentication) How to fix this? I want my test function to display
only after passing through the middle layerI tried something like this:
package main import ( "log" "net/http" "os" "github.com/gin-gonic/gin" "github.com/joho/godotenv" ) func TokenAuthMiddleware() gin.HandlerFunc { err := godotenv.Load(".env") if err != nil { log.Fatal("Erro ao ler variaveis de ambiente") } requiredToken := os.Getenv("API_TOKEN") if requiredToken == "" { log.Fatal("Por favor, defina a variavel API_TOKEN") } return func(c *gin.Context) { token := c.Request.FormValue("api_token") if token == "" { c.JSON(http.StatusBadRequest, gin.H{"message": "Token deve ser preenchido"}) } else if token != requiredToken { c.JSON(http.StatusBadRequest, gin.H{"message": "Token invalido"}) } c.Next() } } func Teste(c *gin.Context) { c.JSON(http.StatusOK, gin.H{ "sucess": "so beautiful", }) } func main() { api := gin.New() v1 := api.Group("v1") v1.Use(TokenAuthMiddleware()) v1.GET("/", Teste) api.Run() }
Thank you very much in advance
You always call c.next()
, it will Continue processing the middleware chain or execute the handler. You need to avoid calling it when the token is incorrect.
func TokenAuthMiddleware() gin.HandlerFunc { err := godotenv.Load(".env") if err != nil { log.Fatal("Erro ao ler variaveis de ambiente") } requiredToken := os.Getenv("API_TOKEN") if requiredToken == "" { log.Fatal("Por favor, defina a variavel API_TOKEN") } return func(c *gin.Context) { token := c.Request.FormValue("api_token") if token == "" { c.JSON(http.StatusBadRequest, gin.H{"message": "Token deve ser preenchido"}) return } if token != requiredToken { c.JSON(http.StatusBadRequest, gin.H{"message": "Token invalido"}) return } c.Next() } }
The above is the detailed content of How to use middleware for authorization - gin gonic go. For more information, please follow other related articles on the PHP Chinese website!