gin icon indicating copy to clipboard operation
gin copied to clipboard

A routing bug?

Open zituocn opened this issue 1 year ago • 3 comments

Description

code:

package main

import (
	"net/http"
	"github.com/gin-gonic/gin"
)

func main() {
	r := gin.Default()
	r.GET("/read_:id.htm", func(c *gin.Context) {
		id := c.Param("id")
		c.JSON(http.StatusOK, gin.H{
			"message": "pong",
			"id":      id,
		})
	})
	r.Run()
}

can match the following requests:

  1. /read_1
  2. /read_1.htm
  3. /read_1.html
  4. /read_1.aaaaaaaa
  5. ......

How to do a unique match?

Environment

  • go version: go1.18.10
  • gin version (or commit ref): v1.8.2
  • operating system:

zituocn avatar Mar 03 '23 09:03 zituocn

Strange usage, maybe you can write id := c.Param("id.htm") Or you can control your route in middleware or function.

Cookiery avatar Mar 14 '23 07:03 Cookiery

Routes should have unique properties

zituocn avatar Mar 15 '23 02:03 zituocn

The router's properties are pretty unique. It just is not the properties we expect here 🙈 According to Gin's radix-tree router, a wild card starts with : and ends at the next / or at the end of the given string. In your example, the wild card is id.htm and not id.


I guess you expected the router to pars something like this:

  • prefix: /read_
  • wildcard: :id
  • postfix: .htm

But as the wildcard ends with the next / or end of the string. So it actually is:

  • prefix: /read_
  • wildcard: :id.htm

pscheid92 avatar May 04 '23 19:05 pscheid92