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.

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

报告相同问题?

悬赏问题

  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示