如何从处理程序内部通过名称调用路由?

时间:2014-05-08 21:41:03

标签: go mux gorilla

如何正确引用内部处理程序中的路径名称?
mux.NewRouter()是全局分配而不是站在函数内?

func AnotherHandler(writer http.ResponseWriter, req *http.Request) {
    url, _ := r.Get("home") // I suppose this 'r' should refer to the router
    http.Redirect(writer, req, url, 302)
}

func main() {
    r := mux.NewRouter()
    r.HandleFunc("/", HomeHandler).Name("home")
    r.HandleFunc("/nothome/", AnotherHandler).Name("another")
    http.Handle("/", r)
    http.ListenAndServe(":8000", nil)
}

1 个答案:

答案 0 :(得分:6)

您有方法mux.CurrentRoute(),它返回给定请求的路由。从该请求中,您可以创建子路由器并调用Get("home")

示例:(播放:http://play.golang.org/p/Lz10YUyP6e

package main

import (
        "fmt"
        "net/http"

        "github.com/gorilla/mux"
)

func HomeHandler(writer http.ResponseWriter, req *http.Request) {
        writer.WriteHeader(200)
        fmt.Fprintf(writer, "Home!!!\n")
}

func AnotherHandler(writer http.ResponseWriter, req *http.Request) {
        url, err := mux.CurrentRoute(req).Subrouter().Get("home").URL()
        if err != nil {
                panic(err)
        }
        http.Redirect(writer, req, url.String(), 302)
}

func main() {
        r := mux.NewRouter()
        r.HandleFunc("/home", HomeHandler).Name("home")
        r.HandleFunc("/nothome/", AnotherHandler).Name("another")
        http.Handle("/", r)
        http.ListenAndServe(":8000", nil)

}