Home  >  Article  >  Backend Development  >  Gin Gonic - colon within URL

Gin Gonic - colon within URL

王林
王林forward
2024-02-08 23:27:30991browse

Gin Gonic - URL 内的冒号

Gin Gonic is a popular Go language web framework that is widely used to build high-performance web applications. When using Gin Gonic, sometimes we need to use colons in the URL path to define parameters, but by default Gin Gonic does not support the use of colons in the URL. So, how do you use colons in URLs? In this article, PHP editor Apple will introduce a simple and effective method to solve this problem so that our Gin Gonic application can support colons in URLs.

Question content

I am creating some REST API using Gin Gonic in Go. I have to expose this endpoint using the following URL: /api/v1/action::request::export I'm using gin gonic to create a route but I'm getting this error "Only one wildcard is allowed per path segment" because the colon ":" is used to map parameters in the URL.

Is there a way to escape the ":" character and use it in URLs?

Thank you

Solution

Like f.s mentioned in the comments, you can just use one pathparam action Then parse it as needed in your code.

Here's an example 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 has its own caveats, and you'll have to handle exceptions and edge cases yourself.

The above is the detailed content of Gin Gonic - colon within URL. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete