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

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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?