doujing5150 2014-05-08 21:41
浏览 27
已采纳

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

How do I properly refer to route names from inside handlers?
Should mux.NewRouter() be assigned globally instead of standing inside a function?

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条回答 默认 最新

  • doujiongqin0687 2014-05-08 23:00
    关注

    You have the method mux.CurrentRoute() that returns the route for a given request. From that request, you can create a subrouter and call Get("home")

    Example: (play: 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!!!
    ")
    }
    
    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)
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 深度学习残差模块模型
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用
  • ¥15 请帮我看一看数电项目如何设计
  • ¥23 (标签-bug|关键词-密码错误加密)