http.Handle和http.HandleFunc之间的区别? [英] Difference between http.Handle and http.HandleFunc?

查看:1084
本文介绍了http.Handle和http.HandleFunc之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Go文档包含以下http包示例:

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

我很难理解Handle和HandleFunc之间的区别以及为什么需要两个。有人可以尝试用清晰的词语来解释一个新的Gopher吗?基本上,HTTP服务器的mux具有一个映射路径 - >处理程序接口

我假设这里使用的接口允许您实现具有状态的复杂路径处理程序。



例如,文件服务器标准包是一个包含文件服务的根目录并实现处理程序接口的结构。



对简单的东西来说,func更简单,更清晰。因此,他们添加了一个特殊的生成器,以便您可以轻松传入func。



请看: server.go



从行:1216(截至今天)

  1216类型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}
pre>

他们正在做的是在自定义类型上实现接口(这恰好匹配接口的api),它只是自己调用它。


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?

解决方案

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.

这篇关于http.Handle和http.HandleFunc之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆