MUX is a router in Go. It helps to route paths to handlers when using go for servers.

Example

mux := http.newServerMux()  
func home(w http.ResponseWriter, r, *http.Request) {  
	//code...  
}  
mux.HandleFunc("/", home)  

How to initialise a router

To initialise a router with mux, you use http.NewServeMux().

URL Patterns

There are a few URL patterns that are supported.

Fixed URL pattern

Fixed URL pattern does not end with a trailing slash user/create. It only triggers when the request URL paths has an exact match.

Subtree URL pattern

Subtree URL pattern does end with a trailing slash user/view/. It works like a wild card and if nothing after the slash matches, this route will be triggered.

Gotchas with mux

There are several things you have to be aware of when using mux.

”/” route works as catch all

When using / as a root route, mux treats it as a catch-all. This means that when none of the paths match, this will be the route that will be executed. this may not always be what you want so may want to add a fallback to your root route.

func home(w http.ResponseWriter, r *http.Request) {  
	if r.URL.Path != "/" {  
		http.NotFound(w,r)  
		return  
	}  
	w.Write([]byte("..."))  
}  

Restrict methods

By default, MUX allows you to use any HTTP Methods which may not be what you want. You have to explicitly restrict those.

func handler(w http.ResponseWriter, r *http.Request) {  
	if r.Method != "POST" {  
		w.Header().Set("Allow", "POST")  
		w.WriteHeader(405)  
		w.Write([]byte("Method not allowed"))  
		return  
	}  
  
	w.Write([]byte("..."))  
}