如何在多路复用中设置路由变量

时间:2014-12-22 05:44:38

标签: go mux

我想将2个网址绑定到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')

1 个答案:

答案 0 :(得分: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)
}