DEV Community

Mike Nithaworn
Mike Nithaworn

Posted on

Golang net.http routing with mux

How to Route Requests?

In order to route, we need a mux. We also use the Handle and HandleFunc functions to setup a mux and allow routing URL paths to custom functions for data processing and responding.

Handle vs HandleFunc

  • Handle takes in a path string and any type that is a Handler. A Handler is anything that implements ServeHTTP with a ResponseWriter and a pointer to a Request.
  • HandleFunc takes in a path string and a function of any name with a ResponseWriter and a pointer to a Request.

Both functions are available in the http package and any custom mux created. Ideally we want to use HandleFunc as it is the more elegant solution.

Create a custom mux:

The following creates a new mux and calls the mux's HandleFunc function that takes in a string for the URL path and a custom function named myFunc with ResponseWriter and a pointer to a Request as arguments. It then uses the newly created mux to listen on port 8080.


func myFunc(res http.ResponseWriter, req *http.Request) {
  fmt.Fprintln(res, "Response from myFunc")
}

func main() {
  mux := http.NewServeMux()
  mux.HandleFunc("/path", myFunc)
  http.ListenAndServe(":8080", mux)
}

Using the default mux:

The following uses HandleFunc from the net.http package and takes in a string for the URL path and a custom function named myFunc with ResponseWriter and a pointer to a Request as arguments. It then uses the DefaultServeMux to listen on port 8080.


func myFunc(res http.ResponseWriter, req *http.Request) {
  fmt.Fprintln(res, "Response from myFunc")
}

func main() {
  http.HandleFunc("/path", myFunc)
  http.ListenAndServe(":8080", nil)
}

In general it is advised to use the DefaultServeMux unless you really need to create your own mux.

HandleFunc vs HandlerFunc?

One thing that can be confusing in the net.http package is that there is a function called HandleFunc which we previously talked about and HandlerFunc (notice the "er") which hasn't been talked about yet.

  • HandleFunc takes a path and function that with a ResponseWriter and a pointer to a Request.
  • HandlerFunc takes a path and a function and converts that function into a Handler.

Feel free to leave any comments and feedback.

Top comments (0)