Home > Backend Development > Golang > How to Combine Multiple http.ServeMux Instances on the Same Port?

How to Combine Multiple http.ServeMux Instances on the Same Port?

Linda Hamilton
Release: 2024-11-02 10:18:02
Original
808 people have browsed it

How to Combine Multiple http.ServeMux Instances on the Same Port?

Combining Multiple http.ServeMux Instances

To serve multiple http.ServeMux instances at the same network address and port, the combinedMux function can be implemented as follows:

<code class="go">func combineMux(muxes ...*http.ServeMux) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        var h http.Handler

        for _, mux := range muxes {
            if h = mux.Handler(r); h != nil {
                h.ServeHTTP(w, r)
                return
            }
        }

        http.NotFound(w, r)
    })
}</code>
Copy after login

This function creates a new http.Handler that iterates through the provided ServeMux instances and serves the first matching handler for the given request. If none are found, a 404 Not Found response is returned.

Alternative Approach: Nesting ServeMux Instances

An alternative way to achieve the same result is to nest the ServeMux instances within each other. This is possible because an http.ServeMux implements the http.Handler interface.

For example, to serve muxA and muxB on the same port and host using this approach:

<code class="go">rootMux := http.NewServeMux()
rootMux.Handle("/muxa/", muxA)
rootMux.Handle("/muxb/", muxB)
http.ListenAndServe(":8080", rootMux)</code>
Copy after login

In this case, the rootMux will handle all requests to its root URL, and it will delegate requests to /muxa/ and /muxb/ to the corresponding ServeMux instances. Note that each nested ServeMux will need to handle its own subpath prefix (e.g., /muxa/ for muxA).

The above is the detailed content of How to Combine Multiple http.ServeMux Instances on the Same Port?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template