dongzang7182 2016-11-08 02:34
浏览 220
已采纳

什么是http请求多路复用器?

I've been studying golang and I noticed a lot of people create servers by using the http.NewServeMux() function and I don't really understand what it does.

I read this:

In go ServeMux is an HTTP request multiplexer. It matches the URL of each incoming request against a list of registered patterns and calls the handler for the pattern that most closely matches the URL.

How is that different than just doing something like:

http.ListenAndServe(addr, nil)
http.Handle("/home", home)
http.Handle("/login", login)

What is the purpose of using multiplexing?

  • 写回答

1条回答 默认 最新

  • douhu2898 2016-11-08 06:11
    关注

    From net/http GoDoc and Source.

    ListenAndServe starts an HTTP server with a given address and handler. The handler is usually nil, which means to use DefaultServeMux. Handle and HandleFunc add handlers to DefaultServeMux

    DefaultServeMux is just a predefined http.ServeMux

    var DefaultServeMux = &defaultServeMux
    var defaultServeMux ServeMux
    

    As you can see http.Handle calls DefaultServeMux internally.

    func Handle(pattern string, handler Handler) { DefaultServeMux.Handle(pattern, handler) }

    The purpose of http.NewServeMux() is to have your own instance of http.Servermux for instances like when you require two http.ListenAndServe functions listening to different ports with different routes.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 求解vmware的网络模式问题
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?