How to Route Multi URL with Same Prefix Using Gin

Gin (Gin-Gonic) is a powerful HTTP web framework. It is famous among Golang Developers. Let’s say you want to route some microservice hosted in your site using prefix url, i.e: this simple code that use Gin will make your life easier. Using RouterGroup feature you can navigate URL with prefix more faster.

package mainimport ""func main() {    r := gin.Default()    v1 := r.Group("/myservice")    {        api := v1.Group("/api/v1")        {            api.GET("/", func(c *gin.Context) {                c.JSON(200, gin.H{                    "message": "Success!",                })            })        }    }    r.Run() // listen and serve on}

When you try to access you will get this logs.

[GIN-debug] GET    /myservice/api/v1/             --> main.main.func1 (3 handlers)

Easy right!

PS: Another syntax to serve url with prefix.

router.GET("/myservice/api/*any", gin.WrapH(http.DefaultServeMux))

Leave a Reply

Your email address will not be published. Required fields are marked *