如何从处理程序中通过其名称调用路由? [英] How to call a route by its name from inside a handler?

查看:147
本文介绍了如何从处理程序中通过其名称调用路由?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何正确引用内部处理程序中的路由名称?

应该全局地分配 mux.NewRouter(),而不是站在函数内部?

  func AnotherHandler(作家http.ResponseWriter,请求* http.Request){
url,_:= r .Get(home)//我想这个'r'应该引用路由器
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)



http://play.golang.org/p/Lz10YUyP6e

  package main 

import(
fmt
net / http

github .com / gorilla / mux


func HomeHandler(作家http.ResponseWriter,请求* http.Request){
writer.WriteHeader(200)
fmt .Fprintf(作家,Home !!! \\\

}

func AnotherHandler(作家http.ResponseWriter,请求* 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)

}


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)
}

解决方案

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!!!\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)

}

这篇关于如何从处理程序中通过其名称调用路由?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆