drzdu44226 2019-02-13 20:23
浏览 210
已采纳

在HTTP vs Mux上使用HandleFunc

I'm new to go and want to set up some routing, as well as cors. I've been seeing two styles of doing so, one that initializes a multiplexer with NewServeMux and then assigns handlers with HandleFunc, and one that uses HandleFunc directly on http. This is what I mean:

mux := http.NewServeMux()
mux.HandleFunc("/api", apiFunc)
mux.HandleFunc("/", indexFunc)

vs

http.HandleFunc("/api", apiFunc)
http.HandleFunc("/", indexFunc)
http.ListenAndServe("127.0.0.1:3001", nil)

Are there any differences with these approaches? If they accomplish similar things, is one more common/pragmatic?

  • 写回答

1条回答 默认 最新

  • doujiazong0322 2019-02-13 20:26
    关注

    http.HandleFunc et al apply your handlers to a package-global instance of the ServeMux held in the http package, which http.ListenAndServe then starts. You can also create your own instance as you did in the first example, which gives you some more control and makes it easier to unit test. In the end, the choice is yours; the convenience functions and package globals are probably fine for smaller projects with a limited maintenance period, but for larger or longer-lived projects I would generally recommend managing your own instances of both ServeMux and Server.

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

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么