func serveHome(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "Welcome to my website!") } func serveAbout(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "This is the About page.") } func main() { mux := http.NewServeMux() mux.HandleFunc("/", serveHome) mux.HandleFunc("/about", serveAbout) http.ListenAndServe(":8080", mux) }
func handleAPI(w http.ResponseWriter, r *http.Request) { //handle API requests } func main() { mux := http.NewServeMux() api := http.StripPrefix("/api/", http.HandlerFunc(handleAPI)) mux.Handle("/api/", api) http.ListenAndServe(":8080", mux) }In this example, we have an API handler function that we only want to be called for URLs that start with "/api/". We use the ServeMux Handle function to register a handler that strips the "/api/" prefix from the URL and calls our handleAPI function with the modified URL. Then, we start the web server again using http.ListenAndServe.