Get URL from gin.Context within custom validator

Hi guys, I’m trying to get the Gin request URL path within a custom validator using a gin.Context reference, but when I invoke the /test2 URL, I can’t get the /test1 URL within the validator, context keeps giving me the /test2 URL, like on the image below;

package main

import (
	"context"
	"fmt"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/validator/v10"
)

// Macro ...
type Macro struct {
	IDMacro   int `db:"idMacro" form:"idMacro" binding:"required_route_oneof=GET;/test1"`
	IDCentral int `db:"idCentral" form:"idCentral" binding:"required_route_oneof=GET;/test1 GET;/test2"`
}

type Validator struct {
	C *gin.Context
}

func (cv *Validator) RequiredRouteOneOf(ctx context.Context, fl validator.FieldLevel) bool {
	fmt.Printf("%s %s\r\n", cv.C.Request.Method, cv.C.Request.URL.Path)
	return true
}

func test1(c *gin.Context) {
	inputData := Macro{}

	if err := c.ShouldBindQuery(&inputData); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
}

func test2(c *gin.Context) {
	inputData := Macro{}

	if err := c.ShouldBindQuery(&inputData); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
}

func main() {
	r := gin.Default()

	// Use the custom validator middleware
	r.Use(func(c *gin.Context) {
		context := &Validator{c}
		_ = binding.Validator.Engine().(*validator.Validate).RegisterValidationCtx("required_route_oneof", context.RequiredRouteOneOf)
		c.Next()
	})

	r.GET("/test1", test1)
	r.GET("/test2", test2)

	r.Run(":3752")
}

Anyone knows why this happens?

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.