如何定义一个中间有 id 的 go-gin 路由

How to define a go-gin route with an id in the middle

我要定义一条路线

/user/{userid}/status

如何定义这种路由并拦截handler中的userid。像这样

 r.GET("/user/{userid}/status", userStatus)

在这种情况下如何读取我的 Go 代码中的 userid 变量?

您可以使用 userid := c.Param("userid"),就像这个工作示例:

package main

import (
    "fmt"
    "net/http"

    "github.com/gin-gonic/gin"
)

func main() {
    router := gin.Default()

    router.GET("/user/:userid/status", func(c *gin.Context) {
        userid := c.Param("userid") 
        message := "userid is " + userid
        c.String(http.StatusOK, message)
        fmt.Println(message)
    })

    router.Run(":8080")
}