Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a route by its name from inside a handler?

Tags:

go

mux

gorilla

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)
}
like image 804
Pierre Prinetti Avatar asked Feb 13 '23 00:02

Pierre Prinetti


1 Answers

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)

}
like image 190
creack Avatar answered Mar 06 '23 19:03

creack