douxia6554 2014-02-22 17:06
浏览 382
已采纳

http.Handle和http.HandleFunc之间的区别?

The Go docs have the following example for the http package:

http.Handle("/foo", fooHandler)
http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
})

I'm having sort of a difficulty understanding the difference between Handle and HandleFunc and why two are needed. Can somebody try to explain to a new Gopher in clear words?

  • 写回答

2条回答 默认 最新

  • douzhang5199 2014-02-22 18:18
    关注

    Basically, the HTTP server's "mux" has a map of path -> handler interface

    Interfaces are used here, I assume, to allow you to implement complex path handlers that have state.

    For example the file server from the standard package is a struct that contains the root dir for file service and implements the handler interface.

    that said, for simple stuff, a func is easier and more clear. So they added a special generator so you can easily pass in a func.

    Take a look at: server.go

    from line: 1216 (as of today)

      1216  type HandlerFunc func(ResponseWriter, *Request)
      1217  
      1218  // ServeHTTP calls f(w, r).
      1219  func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
      1220      f(w, r)
      1221  }
    

    What they are doing is implementing the interface on a custom type (which happens to match the api of the interface) that just calls itself.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题