前往:如何合并两个(或多个)http.ServeMux? [英] Go: How to combine two (or more) http.ServeMux?

查看:52
本文介绍了前往:如何合并两个(或多个)http.ServeMux?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您有两个 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)

如何编写如上所述的 combinedMux 函数?

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

...还是有另一种方法可以完成同一件事?

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

推荐答案

由于 http.ServeMux 也是 http.Handler ,因此您可以轻松地将一个多路复用器嵌套在另一个中,即使在相同的端口和相同的主机名上也是如此.这是执行此操作的一个示例:

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)

请注意,如果没有该 http.StripPrefix()调用,则需要处理整个路径位于下多路复用器中.

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

这篇关于前往:如何合并两个(或多个)http.ServeMux?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆