匹配不同端点的 HTTP 请求 - gorilla mux

HTTP request matching different endpoint - gorilla mux

我有以下处理函数,DataSetsGet 和 RetrieveSharedData。 当使用 URL 提出请求时 https://127.0.0.1:20000/nfdm-fdm/v2/shared-data,我从 DataSetsGet 处理程序而不是 RetrieveSharedData 处理程序函数获得响应。当我将括号从 {id} 取到 id 时,我从 RetrieveSharedData 处理程序得到了正确的响应。任何解决这个问题的帮助,我的代码下面省略了代码。

func DataSetsGet(response http.ResponseWriter, request *http.Request) {

// Data set response codes
}

func RetrieveSharedData(response http.ResponseWriter, request *http.Request) {
// Retrieve shared data response codes
}



type Route struct {
    Name        string
    Method      string
    Pattern     string
    HandlerFunc http.HandlerFunc
}

var Router = NewRouter()

type Routes []Route

func NewRouter() *mux.Router {
    router := mux.NewRouter().StrictSlash(true)
    for _, route := range routes {
        var handler http.Handler
        handler = route.HandlerFunc

        router.
            Methods(route.Method).
            Path(route.Pattern).
            Name(route.Name).
            Handler(handler)
    }

    return router
}


var routes = Routes{
    Route{
        "DataSetsGet",
        strings.ToUpper("Get"),
        "/nfdm-fdm/v2/{id}",
        DataSetsGet,
    },

    Route{
        "RetrieveSharedData",
        strings.ToUpper("Get"),
        "/nfdm-fdm/v2/shared-data",
        RetrieveSharedData,
    },

}


func main{

addr := "127.0.0.1:6060"

server := NewServer(addr)

go func() {
        err := server.ListenAndServe() 
        if err != nil && err != http.ErrServerClosed {
            logger.Log.Errorf("Could not listen on %s: %v\n", addr, err)
        }
    }()
}



// Create a new server
func NewServer(ListAddr string) *http.Server {

    return &http.Server{
        Addr:         ListAddr,
        Handler:      Router,
        ReadTimeout:  5 * time.Second,
        WriteTimeout: 10 * time.Second,
        IdleTimeout:  15 * time.Second,
    }
}


您必须按如下方式修复 dataSetsGet 函数和 route handler function


func DataSetsGet(response http.ResponseWriter, request *http.Request, id string) {
        response.Write([]byte(fmt.Sprintf("myID %s", id)))
}


var routes = Routes{
        Route{
                "DataSetsGet",
                strings.ToUpper("Get"),
                "/nfdm-fdm/v2/dataset/{id}",
                func(w http.ResponseWriter, r *http.Request) {
                        vars := mux.Vars(r)
                        ID := strings.ToLower(vars["id"])
                        DataSetsGet(w, r, ID)
                },
        },

        Route{
                "RetrieveSharedData",
                strings.ToUpper("Get"),
                "/nfdm-fdm/v2/shared-data",
                RetrieveSharedData,
        },
}

卷曲
curl --location --request GET 'http://localhost:6060/nfdm-fdm/v2/dataset/1234'

curl --location --request GET 'http://localhost:6060/nfdm-fdm/v2/shared-data'

我已经更改了 API 路径。正如 mkopriva 所建议的,gorilla mux 无法混合动态和静态片段。

完整的代码片段可以在 playground 此处找到。

只需重新排序您的路由,并确保在正则表达式路由之前包含静态路由,如果在正则表达式路由之前完全匹配,这将导致静态路由优先。

var routes = Routes{
    Route{
        "RetrieveSharedData",
        strings.ToUpper("Get"),
        "/nfdm-fdm/v2/shared-data",
        RetrieveSharedData,
    },
    Route{
        "DataSetsGet",
        strings.ToUpper("Get"),
        "/nfdm-fdm/v2/{id}",
        DataSetsGet,
    },
}