restgo

Gin Gonic - Literal colon inside the URL


I'm creating some REST API with Gin Gonic in go. I have to expose this endpoint with this URL: /api/v1/action::request::export I'm using gin gonic to create the routes and I got this error "only one wildcard per path segment is allowed" because the colon ":" is used to map a parameters in the URL.

There is a way to escape the ":" character and use it into the URL?

Thanks


Solution

  • Like F.S mentioned in comment, you could use just one pathParam action and then in code handle parsing as needed.

    Here is an example that would work for you:

    package main
    
    import (
        "strings"
        "github.com/gin-gonic/gin"
    )
    
    func main() {
        r := gin.Default()
        r.GET("/api/v1/:action", func(c *gin.Context) {
            params, ok := c.Params.Get("action")
            if !ok {
                // handle error
            }
    
            eachParam := strings.SplitN(params, ":", 3)
            request, export := eachParam[1], eachParam[2] // your actual params divided by ":"
    
            c.JSON(200, gin.H{
                "message": "good",
            })
        })
        r.Run()
    }
    
    

    But of course, this approach have its own caveats, you have to handle exceptions and edge cases yourself.