小编典典

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

go

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

阅读 295

收藏
2020-07-02

共1个答案

小编典典

您具有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)

}
2020-07-02