duankuang7928 2015-05-05 21:22
浏览 83
已采纳

什么时候使用Golang的默认MUX而不是自己做[关闭]

I have seen a lot of posts talk about building your own MUX in Go, one of the many examples is here (http://thenewstack.io/building-a-web-server-in-go/).

When should you use the default versus defining your own? The Go docs and none of the blog posts say why you should use one over the other.

  • 写回答

1条回答 默认 最新

  • douyouqian8550 2015-05-05 21:53
    关注

    There are two downsides to the builtin mux:

    1. If you need info from the url (for example id in /users/:id) you have to do it manually:

      http.HandleFunc("/users/", func(res http.ResponseWriter, req *http.Request) {
          id := strings.SplitN(req.URL.Path, "/", 3)[2]
      })
      

      Which is cumbersome.

    2. The default server mux is not the fastest.

    Consider the conclusions from this benchmark:

    First of all, there is no reason to use net/http's default ServeMux, which is very limited and does not have especially good performance. There are enough alternatives coming in every flavor, choose the one you like best.

    So really its only advantage is that everyone already has it since it's included in net/http.

    Lately I've been moving in the direction of avoiding the default http.Handle and http.HandleFunc functions and defining an explicit http.Handler instead, which is then handed to ListenAndServe. (instead of nil:

    handler := http.NewServeMux()
    handler.Handle("/whatever", ...)
    http.ListenAndServe(80, handler)
    

    Newer developers find the distinction between http.Handle and http.HandleFunc subtle and confusing so I think it's worth understanding the http.Handler concept up front. A mux is just another kind of http.Handler (one that routes requests to other http.Handlers) and that reality is hidden away when you rely on the DefaultServeMux.

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

报告相同问题?

悬赏问题

  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。
  • ¥20 CST怎么把天线放在座椅环境中并仿真