1

我想将 2 个 url 绑定到 1 个函数,如下所示。

router.HandleFunc("/_Users", controller.AddResource)
router.HandleFunc("/Resources/{resourceName}", controller.AddResource)

“controller.AddResource”是一个全局函数。如下代码:

function AddResource(req *http.Request, w http.ResponseWriter){
    vars := mux.Vars(req)
    resourceName := vars["resourceName"]
    data = request.Body
    AddDataToResource(resourceName, data)
}

那么如何在第一个路由器中设置vars(resourceName='_User') ?

4

1 回答 1

2

创建一个设置 mux var 的处理程序包装器:

type setVarWrapper struct {
    fn func(http.ResponseWriter, *http.Request)
    name string
    value string
}

func (h *setVarWrapper) ServeHTTP(w http.ResponseWriter, r *http.Request) {
   mux.Vars(req)[h.name] = h.value
   h.fn(w, r)
}

包装用户控制器:

router.Handle("/_Users, &setVarWrapper{fn:controller.AddResource, name:"resourceName", value:"_User"})

一个更简单的选择是编写一个调用通用控制器的 AddUser 函数:

function addUser(req *http.Request, w http.ResponseWriter){
    mux.Vars(req)["resourceName"] = "_User"
    controller.AddResource(w, req)
}

router.HandleFunc("/_Users", addUser)

也许更简单的是在处理程序中检查“”:

function AddResource(req *http.Request, w http.ResponseWriter){
    vars := mux.Vars(req)
    resourceName := vars["resourceName"]
    if resourceName == "" {
       resourceName = "_User"
    }
    data = request.Body
    AddDataToResource(resourceName, data)
}
于 2014-12-22T07:34:30.523 回答