Hello, i need r.GET("/:page",myhandler) ,how do it ?
You can switch the handler with the value from c.Param("page"). Such codes below...
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.New()
r.GET("/:page", func(c *gin.Context) {
switch c.Param("page") {
case "foo":
c.String(http.StatusOK, "Hello, foo!")
case "bar":
c.String(http.StatusOK, "Hello, bar!")
default:
c.String(http.StatusNotFound, "not found")
}
})
r.Run(":5000")
}
$ curl 0:5000/foo
Hello, foo!
$ curl 0:5000/bar
Hello, bar!
$ curl 0:5000/foobar
not found
@delphinus but i can not define other page ,
`
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.New()
r.GET("/:page", func(c *gin.Context) {
switch c.Param("page") {
case "foo":
c.String(http.StatusOK, "Hello, foo!")
case "bar":
c.String(http.StatusOK, "Hello, bar!")
default:
c.String(http.StatusNotFound, "not found")
}
})
r.GET("/admin", func(c *gin.Context) {
c.String(http.StatusOK, "admin page found !")
})
r.Run(":5000")
}
`
[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
- using env: export GIN_MODE=release
- using code: gin.SetMode(gin.ReleaseMode)
[GIN-debug] GET /:page --> main.main.func1 (1 handlers)
[GIN-debug] GET /admin --> main.main.func2 (1 handlers)
panic: path segment 'admin' conflicts with existing wildcard ':page' in path '/admin'
Yes. You cannot do that. The wildcard path :page cannot live together with other concreate paths, such as admin, below the same parent /. You should separate them into other ranks in paths.
r.GET("/admin", ...)
r.GET("/others/:page", ...)
@delphinus I think this is not good.
Not working with root path might affect to SEO or break many website url structures.
Many websites have this structure
domain/abc-$id
but also have
domain/admin
Ability to handle is a must have feature.
I see... , but gin can't achieve that. gin closely depends on httprouter that cannot deal with such cases. ;( You should use the switch-case routing I mentioned above.
func main() {
r := gin.New()
r.GET("/domain/:path", func(c *gin.Context) {
switch p := c.Param("path"); {
case p == "admin":
adminHandler(c)
case strings.HasPrefix(p, "abc-"):
IDstr := strings.TrimPrefix(p, "abc-")
ID, _ := strconv.Atoi(IDstr)
abcHandler(c, ID)
}
})
r.Run(":8080")
}
func adminHandler(c *gin.Context) {
c.String(http.StatusOK, "adminHandler")
}
func abcHandler(c *gin.Context, ID int) {
c.String(http.StatusOK, fmt.Sprintf("abcHandler: %d", ID))
}
@delphinus Good job ! I think i need this , thank you !
closing
Most helpful comment
I see... , but gin can't achieve that. gin closely depends on httprouter that cannot deal with such cases. ;( You should use the switch-case routing I mentioned above.