Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does 'PathPrefix' work in 'gorilla.mux' library for Go?

Tags:

go

gorilla

I'm playing around with the gorilla.mux library for Go. I have the following configuration, but I cant figure out the URL to reach the HelloWorldXml method.

func main() {
    router := mux.NewRouter()
    router.HandleFunc("/{name}.xml", HelloWorldXml).
           PathPrefix("/products/")
    router.HandleFunc("/hello/{name}", HelloWorld)
    http.Handle("/", router)
    http.ListenAndServe(":8787",nil)
}

What would be the proper URL to use? http://localhost:8787/products/MyName.xml returns a 404.

like image 904
Vinnie Avatar asked Sep 10 '13 13:09

Vinnie


People also ask

How does Gorilla mux work?

ServeMux, mux. Router matches incoming requests against a list of registered routes and calls a handler for the route that matches the URL or other conditions. The main features are: Requests can be matched based on URL host, path, path prefix, schemes, header and query values, HTTP methods or using custom matchers.

What is a Subrouter?

Matching Routes Setting the same matching conditions again and again can be boring, so we have a way to group several routes that share the same requirements. We call it “subrouting”. For example, let's say we have several URLs that should only match when the host is www.example.com .

What is go multiplexer?

In go ServeMux is an HTTP request multiplexer. It matches the URL of each incoming request against a list of registered patterns and calls the handler for the pattern that most closely matches the URL.

What is Gorilla mux router?

Gorilla Mux is an HTTP request multiplexer. It is used for request routing and dispatching. It is an extension of the standard ServeMux ; it implements the http. Handler interface.


1 Answers

 func main() {
    router := mux.NewRouter()
    router.HandleFunc("/{name}.xml", HelloWorldXml)
    subrouter := router.PathPrefix("/products/").Subrouter()
    //localhost/products/item.xml
    subrouter.HandleFunc("/{name}.xml", HelloWorldXmlHandler)
    router.HandleFunc("/hello/{name}", HelloWorld)
    http.Handle("/", router)
    http.ListenAndServe(":8787",nil)
}
like image 95
Minty Avatar answered Sep 29 '22 09:09

Minty