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

后端 未结 2 2068
再見小時候
再見小時候 2021-02-06 14:24

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.ServeMu         


        
2条回答
  •  花落未央
    2021-02-06 14:46

    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.

提交回复
热议问题