译注: 这篇文章的内容很是基础,也很是容易理解。原文地址,感受是最能清晰的讲述了net/http
包的用法的一篇,故翻译一下共享之。golang
Go 语言中处理 HTTP 请求主要跟两个东西相关:ServeMux
和 Handler
。数据库
ServrMux
本质上是一个 HTTP 请求路由器(或者叫多路复用器,Multiplexor)。它把收到的请求与一组预先定义的 URL 路径列表作对比,而后在匹配到路径的时候调用关联的处理器(Handler)。浏览器
处理器(Handler)负责输出HTTP响应的头和正文。任何知足了http.Handler
接口的对象均可做为一个处理器。通俗的说,对象只要有个以下签名的ServeHTTP
方法便可:bash
ServeHTTP(http.ResponseWriter, *http.Request)
Go 语言的 HTTP 包自带了几个函数用做经常使用处理器,好比FileServer
,NotFoundHandler
和 RedirectHandler
。咱们从一个简单具体的例子开始:服务器
$ mkdir handler-example $ cd handler-example $ touch main.go
//File: main.go package main import ( "log" "net/http" ) func main() { mux := http.NewServeMux() rh := http.RedirectHandler("http://example.org", 307) mux.Handle("/foo", rh) log.Println("Listening...") http.ListenAndServe(":3000", mux) }
快速地过一下代码:闭包
在 main
函数中咱们只用了 http.NewServeMux
函数来建立一个空的 ServeMux
。函数
而后咱们使用 http.RedirectHandler
函数建立了一个新的处理器,这个处理器会对收到的全部请求,都执行307重定向操做到 http://example.org
。测试
接下来咱们使用 ServeMux.Handle
函数将处理器注册到新建立的 ServeMux
,因此它在 URL 路径/foo
上收到全部的请求都交给这个处理器。编码
最后咱们建立了一个新的服务器,并经过 http.ListenAndServe
函数监听全部进入的请求,经过传递刚才建立的 ServeMux
来为请求去匹配对应处理器。.net
继续,运行一下这个程序:
$ go run main.go Listening...
而后在浏览器中访问 http://localhost:3000/foo
,你应该能发现请求已经成功的重定向了。
明察秋毫的你应该能注意到一些有意思的事情:ListenAndServer
的函数签名是 ListenAndServe(addr string, handler Handler)
,可是第二个参数咱们传递的是个 ServeMux
。
咱们之因此能这么作,是由于 ServeMux
也有 ServeHTTP
方法,所以它也是个合法的 Handler
。
对我来讲,将 ServerMux
用做一个特殊的Handler是一种简化。它不是本身输出响应而是将请求传递给注册到它的其余 Handler。这乍一听起来不是什么明显的飞跃 - 但在 Go 中将 Handler
链在一块儿是很是广泛的用法。
让咱们建立一个自定义的处理器,功能是将以特定格式输出当前的本地时间:
type timeHandler struct { format string } func (th *timeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { tm := time.Now().Format(th.format) w.Write([]byte("The time is: " + tm)) }
这个例子里代码自己并非重点。
真正的重点是咱们有一个对象(本例中就是个timerHandler
结构体,可是也能够是一个字符串、一个函数或者任意的东西),咱们在这个对象上实现了一个 ServeHTTP(http.ResponseWriter, *http.Request)
签名的方法,这就是咱们建立一个处理器所需的所有东西。
咱们把这个集成到具体的示例里:
//File: main.go package main import ( "log" "net/http" "time" ) type timeHandler struct { format string } func (th *timeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { tm := time.Now().Format(th.format) w.Write([]byte("The time is: " + tm)) } func main() { mux := http.NewServeMux() th := &timeHandler{format: time.RFC1123} mux.Handle("/time", th) log.Println("Listening...") http.ListenAndServe(":3000", mux) }
main
函数中,咱们像初始化一个常规的结构体同样,初始化了timeHandler
,用 &
符号得到了其地址。随后,像以前的例子同样,咱们使用 mux.Handle
函数来将其注册到 ServerMux
。
如今当咱们运行这个应用,ServerMux
将会将任何对 /time
的请求直接交给 timeHandler.ServeHTTP
方法处理。
访问一下这个地址看一下效果:http://localhost:3000/time 。
注意咱们能够在多个路由中轻松的复用 timeHandler
:
func main() { mux := http.NewServeMux() th1123 := &timeHandler{format: time.RFC1123} mux.Handle("/time/rfc1123", th1123) th3339 := &timeHandler{format: time.RFC3339} mux.Handle("/time/rfc3339", th3339) log.Println("Listening...") http.ListenAndServe(":3000", mux) }
对于简单的状况(好比上面的例子),定义个新的有 ServerHTTP
方法的自定义类型有些累赘。咱们看一下另一种方式,咱们借助 http.HandlerFunc
类型来让一个常规函数知足做为一个 Handler
接口的条件。
任何有 func(http.ResponseWriter, *http.Request)
签名的函数都能转化为一个 HandlerFunc
类型。这颇有用,由于 HandlerFunc
对象内置了 ServeHTTP
方法,后者能够聪明又方便的调用咱们最初提供的函数内容。
若是你听起来还有些困惑,能够尝试看一下[相关的源代码]http://golang.org/src/pkg/net...。你将会看到让一个函数对象知足 Handler
接口是很是简洁优雅的。
让咱们使用这个技术从新实现一遍timeHandler
应用:
//File: main.go package main import ( "log" "net/http" "time" ) func timeHandler(w http.ResponseWriter, r *http.Request) { tm := time.Now().Format(time.RFC1123) w.Write([]byte("The time is: " + tm)) } func main() { mux := http.NewServeMux() // Convert the timeHandler function to a HandlerFunc type th := http.HandlerFunc(timeHandler) // And add it to the ServeMux mux.Handle("/time", th) log.Println("Listening...") http.ListenAndServe(":3000", mux) }
实际上,将一个函数转换成 HandlerFunc
后注册到 ServeMux
是很广泛的用法,因此 Go 语言为此提供了个便捷方式:ServerMux.HandlerFunc
方法。
咱们使用便捷方式重写 main()
函数看起来是这样的:
func main() { mux := http.NewServeMux() mux.HandleFunc("/time", timeHandler) log.Println("Listening...") http.ListenAndServe(":3000", mux) }
绝大多数状况下这种用函数当处理器的方式工做的很好。可是当事情开始变得更复杂的时候,就会有些产生一些限制了。
你可能已经注意到了,跟以前的方式不一样,咱们不得不将时间格式硬编码到 timeHandler
的方法中。若是咱们想从 main()
函数中传递一些信息或者变量给处理器该怎么办?
一个优雅的方式是将咱们处理器放到一个闭包中,将咱们要使用的变量带进去:
//File: main.go package main import ( "log" "net/http" "time" ) func timeHandler(format string) http.Handler { fn := func(w http.ResponseWriter, r *http.Request) { tm := time.Now().Format(format) w.Write([]byte("The time is: " + tm)) } return http.HandlerFunc(fn) } func main() { mux := http.NewServeMux() th := timeHandler(time.RFC1123) mux.Handle("/time", th) log.Println("Listening...") http.ListenAndServe(":3000", mux) }
timeHandler
函数如今有了个更巧妙的身份。除了把一个函数封装成 Handler(像咱们以前作到那样),咱们如今使用它来返回一个处理器。这种机制有两个关键点:
首先是建立了一个fn
,这是个匿名函数,将 format
变量封装到一个闭包里。闭包的本质让处理器在任何状况下,均可以在本地范围内访问到 format
变量。
其次咱们的闭包函数知足 func(http.ResponseWriter, *http.Request)
签名。若是你记得以前咱们说的,这意味咱们能够将它转换成一个HandlerFunc
类型(知足了http.Handler
接口)。咱们的timeHandler
函数随后转换后的 HandlerFunc
返回。
在上面的例子中咱们已经能够传递一个简单的字符串给处理器。可是在实际的应用中可使用这种方法传递数据库链接、模板组,或者其余应用级的上下文。使用全局变量也是个不错的选择,还能获得额外的好处就是编写更优雅的自包含的处理器以便测试。
你也可能见过相同的写法,像这样:
func timeHandler(format string) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { tm := time.Now().Format(format) w.Write([]byte("The time is: " + tm)) }) }
或者在返回时,使用一个到 HandlerFunc
类型的隐式转换:
func timeHandler(format string) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { tm := time.Now().Format(format) w.Write([]byte("The time is: " + tm)) } }
你可能已经在不少地方看到过 DefaultServeMux
, 从最简单的 Hello World
例子,到 go 语言的源代码中。
我花了很长时间才意识到 DefaultServerMux
并无什么的特殊的地方。DefaultServerMux
就是咱们以前用到的 ServerMux
,只是它随着 net/httpp
包初始化的时候被自动初始化了而已。Go 源代码中的相关行以下:
var DefaultServeMux = NewServeMux()
net/http
包提供了一组快捷方式来配合 DefaultServeMux
:http.Handle
和 http.HandleFunc
。这些函数与咱们以前看过的相似的名称的函数功能同样,惟一的不一样是他们将处理器注册到 DefaultServerMux
,而以前咱们是注册到本身建立的 ServeMux
。
此外,ListenAndServe
在没有提供其余的处理器的状况下(也就是第二个参数设成了 nil
),内部会使用 DefaultServeMux
。
所以,做为最后一个步骤,咱们使用 DefaultServeMux
来改写咱们的 timeHandler
应用:
//File: main.go package main import ( "log" "net/http" "time" ) func timeHandler(format string) http.Handler { fn := func(w http.ResponseWriter, r *http.Request) { tm := time.Now().Format(format) w.Write([]byte("The time is: " + tm)) } return http.HandlerFunc(fn) } func main() { // Note that we skip creating the ServeMux... var format string = time.RFC1123 th := timeHandler(format) // We use http.Handle instead of mux.Handle... http.Handle("/time", th) log.Println("Listening...") // And pass nil as the handler to ListenAndServe. http.ListenAndServe(":3000", nil) }