未找到路线组的 Go Gin-Gonic 句柄

问题描述 投票:0回答:1

我想知道如何让 Go Gin-Gonic Web 服务器来处理特定组的未找到路由。如果我有以下代码:

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

    // handle /sub routes

    rGroup := r.Group("/sub")
    {
        rGroup.GET("/a", func(c *gin.Context) {
            // respond found /sub/a
        })

        rGroup.NoRoute(func(c *gin.Context) { // this fails, NoRoute is not available
            // respond not found in /sub
        })
    }

    // handle / routes

    r.GET("/a", func(c *gin.Context) {
        // respond found /a
    })

    r.NoRoute(func(c *gin.Context) {
        // respond not found in /
    })

    r.Run(":8000")
}

然后它适用于

/
路线,但集团没有
NoRoute
方法,那么还有其他方法可以实现同样的效果吗?

go routes go-gin
1个回答
0
投票
Gin does support this. Inside the NoRoute, You can do different logic based the gin.Context and return different results.

经过一些研究,Gin 目前似乎并不直接支持这一点。相反,可以使用

NoRoute

以不同的方式实现

这是一个示例实现;我希望这有帮助。

package main

import (
    "net/http"
    "strings"

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

func notFoundHandler(c *gin.Context) {
    // check the path is /sub
    if strings.HasPrefix(c.Request.URL.Path, "/sub/") {
        c.JSON(http.StatusNotFound, gin.H{"message": "Route not found in /sub"})
        c.Abort()
    }

    // check the path is /v1
    if strings.HasPrefix(c.Request.URL.Path, "/v1/") {
        c.JSON(http.StatusNotFound, gin.H{"message": "Route not found in /v1"})
        c.Abort()
    }
}

func main() {
    r := gin.Default()
    v1 := r.Group("/v1")
    {

        v1.GET("/a", func(c *gin.Context) {
            c.JSON(200, gin.H{"message": "inside v1 a"})
            return
        })

    }

    rGroup := r.Group("/sub")
    {

        rGroup.GET("/a", func(c *gin.Context) {
            c.JSON(200, gin.H{"message": "inside sub a"})
            return
        })

    }
    r.NoRoute(notFoundHandler)

    r.Run(":8000")
}

参考:

© www.soinside.com 2019 - 2024. All rights reserved.