express - Golang httpRouter 在与函数 slice 一起使用时返回最后一个响应

标签 express go function-pointers slice router

我正在尝试为 httprouter 包实现类似 expressjs 的功能。 我创建了一个结构 type mounter

type Mounter struct {
    BasePath string
    Routes   []*Route
}

和一个代表子路由的Route结构

type Route struct {
    Path   string
    Method string
    Func   Handle
}

类型 Handle func(http.ResponseWriter, *http.Request, Params)

类型参数接口(interface){}

我有一个 NewRoutes 函数,这是我想从 expressjs 移植的主要功能,新路由与 express.Router

做同样的事情
func NewRoutes(base string) (mounter *Mounter) {
    mounter = &Mounter{
        BasePath: base,
    }
    return
}

我在 *Mounter 下有 get post put delete 方法

//GET request handler
func (mounter *Mounter) GET(path string, Func Handle) {
    mounter.Routes = append(mounter.Routes, &Route{path, "get", Func})
}

//POST request handler
func (mounter *Mounter) POST(path string, Func Handle) {
    mounter.Routes = append(mounter.Routes, &Route{path, "post", Func})
}

//PUT request handler
func (mounter *Mounter) PUT(path string, Func Handle) {
    mounter.Routes = append(mounter.Routes, &Route{path, "put", Func})
}

//DELETE request handler
func (mounter *Mounter) DELETE(path string, Func Handle) {
    mounter.Routes = append(mounter.Routes, &Route{path, "delete", Func})
}

最后我有一个将路由器安装到实际路由器的 Mount 方法

func (mounter *Mounter) Mount(router *rtr.Router) {
    mounter.BasePath = strings.TrimSuffix(mounter.BasePath, "/")
    for _, route := range mounter.Routes {
        path := route.Path
        if !strings.HasSuffix(path, "/") {
            path += "/"
        }
        path = mounter.BasePath + path
        switch strings.ToLower(route.Method) {
        case "get":
            router.GET(path, func(res http.ResponseWriter, req *http.Request, params rtr.Params) {
                route.Func(res, req, params)
            })
        case "post":
            router.POST(path, func(res http.ResponseWriter, req *http.Request, params rtr.Params) {
                route.Func(res, req, params)
            })
        case "delete":
            router.DELETE(path, func(res http.ResponseWriter, req *http.Request, params rtr.Params) {
                route.Func(res, req, params)
            })
        case "put":
            router.PUT(path, func(res http.ResponseWriter, req *http.Request, params rtr.Params) {
                route.Func(res, req, params)
            })
        }
    }
}

一切都很好,方法也很好,如果我尝试向 get 端点发送一个 post 请求,它会给出一个很好的 404,但唯一的问题是它总是响应最后添加的成员的处理程序,而不考虑子路径,所以

package api
var ApiRouter = express.NewRoutes("/api/")

func init() {
    ApiRouter.GET("/", func(res http.ResponseWriter, req *http.Request, _ express.Params) {
        fmt.Fprintln(res, "testget/")
    })
    ApiRouter.GET("/pt", func(res http.ResponseWriter, req *http.Request, _ express.Params) {
        fmt.Fprintln(res, "pt")
    })
    ApiRouter.POST("/test", func(res http.ResponseWriter, req *http.Request, _ express.Params) {
        fmt.Fprintln(res, "test/post")
    })
}

package main
func main() {
    router := express.New()
    api.ApiRouter.Mount(router)
    for _, route := range api.ApiRouter.Routes {
        fmt.Println(*route)
    }
    router.ServeFiles("/public/*filepath", http.Dir("./public/"))
    http.ListenAndServe(":1024", router)
}

将始终响应 test/post 并且我在上面出于测试目的所做的 range 的输出是 那么你知道为什么它总是使用相同的函数来响应但完美地识别路径吗?

最佳答案

问题出在Mount 方法,即Iteration Variables and Closures .声明一个用于捕获 route 的新变量,例如

thisRoute := route //capture iteration variable
switch strings.ToLower(route.Method) {
case "get":
    router.GET(path, func(res http.ResponseWriter, req *http.Request, params rtr.Params) {
        thisRoute.Func(res, req, params)
    })
case "post":
    router.POST(path, func(res http.ResponseWriter, req *http.Request, params rtr.Params) {
        thisRoute.Func(res, req, params)
    })
//...
}

关于express - Golang httpRouter 在与函数 slice 一起使用时返回最后一个响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39905623/

相关文章:

javascript - Jade with Express 中有 2 个带有隐藏方法的 Form

reactjs - 如何使用expressJS提供ReactJS静态文件?

javascript - JS 错误为 : var is not defined. 我如何发送函数值

c++ - C++中的函数指针与仿函数

c++ - 获取指向非静态成员函数的函数指针

node.js - 创建 Stormpath 用户并在一次调用中分配给组

go - VSCODE 无法在 go 模块中安装工具

bash - 无法从GoLang中的/etc/profile获取环境变量

go - 在go中创建一个具有普通权限的目录

c - 如何在没有类型定义的情况下在一行中声明多个函数指针?