In Go, the http.ServeMux is a convenient way to handle and route HTTP requests. However, you may encounter situations where you need to combine two or more instances of http.ServeMux and serve them simultaneously at the same port number.
Instead of writing a separate combinedMux function, you can utilize the fact that http.ServeMux implements the http.Handler interface. This allows you to nest one mux inside another:
<code class="go">rootMux := http.NewServeMux() subMuxA := http.NewServeMux() subMuxB := http.NewServeMux() // Initialize muxA and muxB with their respective handlers // Handle requests for "/sub_path/a" in subMuxA subMuxA.HandleFunc("/sub_path/a", myHandleFuncA) // Handle requests for "/sub_path/b" in subMuxB subMuxB.HandleFunc("/sub_path/b", myHandleFuncB) // Nest subMuxA and subMuxB under "/top_path" in rootMux rootMux.Handle("/top_path/a", subMuxA) rootMux.Handle("/top_path/b", subMuxB) http.ListenAndServe(":8080", rootMux)</code>
In this example:
By nesting http.ServeMux instances, you can easily combine multiple muxes and serve them at the same port, providing a flexible and efficient way to handle different types of requests in your Go application.
The above is the detailed content of How to Combine Multiple http.ServeMux Instances in Go?. For more information, please follow other related articles on the PHP Chinese website!