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 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab