Last active
May 11, 2021 15:18
-
-
Save vindard/6dcf5b006964b1f85f025d72a311639a to your computer and use it in GitHub Desktop.
A demo of the different ways to hit http.ServeMux (standard library router) when making a webserver in Go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Context: https://rickyanto.com/understanding-go-standard-http-libraries-servemux-handler-handle-and-handlefunc/ | |
package main | |
import ( | |
"fmt" | |
"net/http" | |
) | |
func handlerFunc(w http.ResponseWriter, r *http.Request) { | |
// w.Header().Set("Content-Type", "text/html") | |
fmt.Fprintf(w, "Hello World!") | |
} | |
type Sample struct{} | |
func (s *Sample) ServeHTTP(w http.ResponseWriter, r *http.Request) { | |
fmt.Fprint(w, "Hello World") | |
} | |
// A sample implementation to demonstrate the different ways | |
// to route using the net/http package. | |
// | |
// Version 1: | |
// Simplest method, define a 'HandlerFunc' interface and pass it | |
// to the http.HandleFunc method. Internally, http instantiates | |
// its own default ServeMux and passes the args on that that | |
// ServeMux object's 'HandleFunc' method | |
// | |
// Version 2: | |
// Define a struct that implements the HandleFunc interface in a | |
// 'ServeHTTP' method. Pass a pointer to the an instance of the | |
// struct to http.Handle. http passes it on to its internal default | |
// ServeMux.Handle method. | |
// | |
// Version 3: | |
// Same as Version 1 except we explictly instantiate an http.ServeMux, | |
// call the HandleFunc methodon that instance instead, and then pass | |
// that instance into http.ListenAndServe. | |
// | |
// Version 4: | |
// Same as Version 2 except we explictly instantiate an http.ServeMux, | |
// call the Handle method on that instance instead, and then pass that | |
// instance into http.ListenAndServe. | |
// | |
// Uncomment according to the 'Version' comments below to see the | |
// different options in action. | |
func serveDemo() { | |
// Handle-compatible interface | |
// t := Sample{} // Version 2, Version 4 | |
// http default ServeMux | |
http.HandleFunc("/", handlerFunc) // Version 1 | |
// http.Handle("/", &t) // Version 2 | |
// Explicit ServeMux instance | |
// r := http.NewServeMux() // Version 3, Version 4 | |
// r.HandleFunc("/", handlerFunc) // Version 3 | |
// r.Handle("/", &t) // Version 4 | |
fmt.Println("Server started at localhost:3000") | |
http.ListenAndServe(":3000", nil) // Version 1, Version 2 | |
// http.ListenAndServe(":3000", r) // Version 3, Version 4 | |
} | |
func main() { | |
serveDemo() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment