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条)

报告相同问题?

悬赏问题

  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)