Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Go 如何从处理程序内部按名称调用路由?_Go_Mux_Gorilla - Fatal编程技术网

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

Go 如何从处理程序内部按名称调用路由?,go,mux,gorilla,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 ma

如何从内部处理程序正确引用路由名称?
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)
}

您可以使用方法
mux.CurrentRoute()
返回给定请求的路由。根据该请求,您可以创建一个子程序并调用
Get(“home”)

示例:(播放:)


如果在第一次请求后未找到404页,这是因为
Subrouter()
更改了路由(它执行
r.addMatcher(路由器)
)。看,我现在还没有找到更好的方法。。。
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)

}