英文:
How to set route vars in mux
问题
我想将两个URL绑定到一个函数上,就像下面这样。
router.HandleFunc("/_Users", controller.AddResource)
router.HandleFunc("/Resources/{resourceName}", controller.AddResource)
controller.AddResource
是一个全局函数,代码如下:
func AddResource(req *http.Request, w http.ResponseWriter) {
vars := mux.Vars(req)
resourceName := vars["resourceName"]
data := req.Body
AddDataToResource(resourceName, data)
}
那么我该如何在第一个路由器中设置 vars(resourceName='_User')
呢?
英文:
I want to bind 2 urls to 1 function, like below.
router.HandleFunc("/_Users", controller.AddResource)
router.HandleFunc("/Resources/{resourceName}", controller.AddResource)
the "controller.AddResource" is a global function. the code like below:
function AddResource(req *http.Request, w http.ResponseWriter){
vars := mux.Vars(req)
resourceName := vars["resourceName"]
data = request.Body
AddDataToResource(resourceName, data)
}
so how can I set the vars(resourceName='_User') in the first router?
答案1
得分: 2
创建一个设置mux变量的处理程序包装器:
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(r)[h.name] = h.value
h.fn(w, r)
}
包装用户控制器:
router.Handle("/_Users", &setVarWrapper{fn: controller.AddResource, name: "resourceName", value: "_User"})
一个更简单的选项是编写一个调用通用控制器的AddUser函数:
func addUser(req *http.Request, w http.ResponseWriter) {
mux.Vars(req)["resourceName"] = "_User"
controller.AddResource(w, req)
}
router.HandleFunc("/_Users", addUser)
甚至更简单的方法是在处理程序中检查空字符串:
func AddResource(req *http.Request, w http.ResponseWriter) {
vars := mux.Vars(req)
resourceName := vars["resourceName"]
if resourceName == "" {
resourceName = "_User"
}
data := request.Body
AddDataToResource(resourceName, data)
}
英文:
Create a handler wrapper that sets the 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)
}
Wrap the user controller:
router.Handle("/_Users, &setVarWrapper{fn:controller.AddResource, name:"resourceName", value:"_User"})
A simpler option is to write an AddUser function that calls through to the generic controller:
function addUser(req *http.Request, w http.ResponseWriter){
mux.Vars(req)["resourceName"] = "_User"
controller.AddResource(w, req)
}
router.HandleFunc("/_Users", addUser)
Perhaps even simpler is to check for "" in the handler:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论