package main import ( "fmt" "net/http" "github.com/gorilla/mux" ) func main() { r := mux.NewRouter() r.HandleFunc("/", helloHandler) http.Handle("/", r) http.ListenAndServe(":8080", nil) } func helloHandler(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "Hello, world!") }
package main import ( "fmt" "net/http" "github.com/gorilla/mux" ) func main() { r := mux.NewRouter() r.HandleFunc("/users/{username}", userHandler).Methods("GET").Name("user") r.Use(loggingMiddleware) http.Handle("/", r) http.ListenAndServe(":8080", nil) } func userHandler(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) username := vars["username"] fmt.Fprintf(w, "User profile page for %s", username) } func loggingMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Printf("%s %s\n", r.Method, r.URL.Path) next.ServeHTTP(w, r) }) }In this example, we register a route with a URL variable named "username". We also specify that this route only responds to GET requests and give it a name for later reference. Additionally, we register an inline middleware function that simply logs each incoming request method and path to the console. The userHandler function retrieves the username variable from the request context and writes a response with the username. Overall, the gorilla/mux library is a powerful tool for handling HTTP routing and dispatching in Go. By registering routes and middleware functions, we can easily handle incoming requests and send appropriate responses.