当与函数片一起使用时,Golang httpRouter返回最后一个响应

时间:2016-10-06 21:05:47

标签: express go function-pointers slice router

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

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

和代表subRoutes的Route结构

type Route struct {
    Path   string
    Method string
    Func   Handle
}

type Handle func(http.ResponseWriter, *http.Request, Params)

type Params interface{}

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

相同
func NewRoutes(base string) (mounter *Mounter) {
    mounter = &Mounter{
        BasePath: base,
    }
    return
}

我在get post put delete

下有*Mounter个方法
//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端点,它提供了一个很好的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输出用于测试目的 那么你是否知道为什么它总是使用相同的函数来响应但是完全识别路径?

1 个答案:

答案 0 :(得分:1)

问题在于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)
    })
//...
}