httpgoservemux

Go: How to combine two (or more) http.ServeMux?


Given that you have two instances of http.ServeMux, and you wish for them to be served at the same port number, like so:

    muxA, muxB http.ServeMux
    //initialise muxA
    //initialise muxB
    combinedMux := combineMux([muxA, muxB])
    http.ListenAndServe(":8080", combinedMux)

How would one go about writing the combinedMux function, as described above?

... or is there an alternative way to accomplish the same thing?


Solution

  • Because an http.ServeMux is also an http.Handler you can easily nest one mux inside another, even on the same port and same hostname. Here's one example of doing that:

    rootMux := http.NewServeMux()
    subMux := http.NewServeMux()
    
    // This will end up handling /top_path/sub_path
    subMux.HandleFunc("/sub_path", myHandleFunc)
    
    // Use the StripPrefix here to make sure the URL has been mapped
    // to a path the subMux can read
    rootMux.Handle("/top_path/", http.StripPrefix("/top_path", subMux))
    
    http.ListenAndServe(":8000", rootMux)
    

    Note that without that http.StripPrefix() call, you would need to handle the whole path in the lower mux.