Gin Gonic - colon within URL

王林
Release: 2024-02-08 23:27:30
forward
1013 people have browsed it

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()
}

Copy after login

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!

Related labels:
source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!