Making and Using HTTP Middleware
Making and Using HTTP Middleware
Making and Using HTTP Middleware
- 原文地址:Making and Using HTTP Middleware
- 原文作者:Alex Edwards
- 译文出处: https://www.alexedwards.net/
- 本文永久链接:https://github.com/gocn/translator/blob/master/2019/w17_Making_and_Using_HTTP_Middleware.md
- 译者:咔叽咔叽
- 校对:fivezh
在构建 Web 应用程序时,可能需要为很多(甚至所有)的 HTTP 请求运行一些共享的功能。在执行一些繁重的处理之前,你可能想给每个请求记录日志,用 gzip 压缩每个返回数据或者检查缓存。
实现这种共享功能的一种方法是将其设置为中间件 - 它在正常的应用处理程序之前或之后用自包含代码的方式独立地处理请求。在 Go 中,使用中间件的常见位置是 ServeMux 和应用处理程序之间,因此 HTTP 请求的控制流程如下所示:
1ServeMux => Middleware Handler => Application Handler
在这篇文章中,我将解释如何实现这种模式下的自定义中间件,并运行一些使用第三方中间件的具体示例。
基本原则
在 Go 中实现和使用中间件基本上是比较简单的。我们需要以下几点:
- 实现我们的中间件,使它满足http.Handler接口。
- 构建链式的处理程序,包含我们的中间件处理程序和我们的普通应用处理程序,我们可以使用http.ServeMux进行注册。
我将解释具体的实现方法。
希望你已经熟悉了下面构造处理程序的方法(如果没有,最好在继续之前先阅读入门手册)。
1func messageHandler(message string) http.Handler {
2 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
3 w.Write([]byte(message)
4 })
5}
在这个处理程序中,我们将逻辑(一个简单的w.Write
)放在一个匿名函数中,然后引用函数体外的message
变量以形成一个闭包。接下来,我们通过使用http.HandlerFunc适配器来将此闭包转换为处理程序,然后返回它。
我们可以使用相同的方法来实现链式的处理程序,可以不用将字符串传递给闭包(如上所述),而是将链中的下一个处理程序作为变量传递,然后通过调用它的ServeHTTP()
方法将控制转移到下一个处理程序。
下面提供了一个构建中间件的完整模式:
1func exampleMiddleware(next http.Handler) http.Handler {
2 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
3 // Our middleware logic goes here...
4 next.ServeHTTP(w, r)
5 })
6}
你将注意到此中间件函数有一个func(http.Handler) http.Handler
的函数签名。它接收一个处理程序作为参数并返回另一个处理程序。这有两个原因:
- 因为它返回一个处理程序,我们可以直接使用标准库 net/http 包提供的 ServeMux 来注册中间件函数。
- 我们可以通过将中间件函数嵌套在彼此内部来实现任意长的链式处理程序。例如:
1http.Handle("/", middlewareOne(middlewareTwo(finalHandler)))
控制流程的说明
让我们看一个简化的示例,其中包含一些只是将日志消息写入 stdout 的中间件:
File: main.go
1package main
2
3import (
4 "log"
5 "net/http"
6)
7
8func middlewareOne(next http.Handler) http.Handler {
9 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
10 log.Println("Executing middlewareOne")
11 next.ServeHTTP(w, r)
12 log.Println("Executing middlewareOne again")
13 })
14}
15
16func middlewareTwo(next http.Handler) http.Handler {
17 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
18 log.Println("Executing middlewareTwo")
19 if r.URL.Path != "/" {
20 return
21 }
22 next.ServeHTTP(w, r)
23 log.Println("Executing middlewareTwo again")
24 })
25}
26
27func final(w http.ResponseWriter, r *http.Request) {
28 log.Println("Executing finalHandler")
29 w.Write([]byte("OK"))
30}
31
32func main() {
33 finalHandler := http.HandlerFunc(final)
34
35 http.Handle("/", middlewareOne(middlewareTwo(finalHandler)))
36 http.ListenAndServe(":3000", nil)
37}
运行此应用程序并请求http://localhost:3000。你应该能看到类似的日志输出:
1$ go run main.go
22014/10/13 20:27:36 Executing middlewareOne
32014/10/13 20:27:36 Executing middlewareTwo
42014/10/13 20:27:36 Executing finalHandler
52014/10/13 20:27:36 Executing middlewareTwo again
62014/10/13 20:27:36 Executing middlewareOne again
很显然可以看到程序依据处理链嵌套的顺序来传递控制,然后再以相反的方向返回。
我们随时可以通过让中间件处理程序使用return
来停止控制在链中的传播。
在上面的例子中,我在middlewareTwo
函数中包含了一个满足条件的返回。尝试访问http://localhost:3000/foo并再次检查日志 - 你会看到,这次请求在通过中间件调用链的时候不会超过middlewareTwo
。
理解了吗,再来一个恰当的例子如何
好吧,假设我们正在构建一个处理 XML 格式请求的服务。我们想创建一些中间件,a)检查请求体的存在,b)确保请求体是 XML 格式。如果其中任何一项检查失败,我们希望中间件写入错误消息并阻止请求到达我们的应用处理程序。
File: main.go
1package main
2
3import (
4 "bytes"
5 "net/http"
6)
7
8func enforceXMLHandler(next http.Handler) http.Handler {
9 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
10 // Check for a request body
11 if r.ContentLength == 0 {
12 http.Error(w, http.StatusText(400), 400)
13 return
14 }
15 // Check its MIME type
16 buf := new(bytes.Buffer)
17 buf.ReadFrom(r.Body)
18 if http.DetectContentType(buf.Bytes()) != "text/xml; charset=utf-8" {
19 http.Error(w, http.StatusText(415), 415)
20 return
21 }
22 next.ServeHTTP(w, r)
23 })
24}
25
26func main() {
27 finalHandler := http.HandlerFunc(final)
28
29 http.Handle("/", enforceXMLHandler(finalHandler))
30 http.ListenAndServe(":3000", nil)
31}
32
33func final(w http.ResponseWriter, r *http.Request) {
34 w.Write([]byte("OK"))
35}
看起来好像没毛病。让我们创建一个简单的 XML 文件来测试它:
1$ cat > books.xml
2<?xml version="1.0"?>
3<books>
4 <book>
5 <author>H. G. Wells</author>
6 <title>The Time Machine</title>
7 <price>8.50</price>
8 </book>
9</books>
使用 cURL 来发送一些请求:
1$ curl -i localhost:3000
2HTTP/1.1 400 Bad Request
3Content-Type: text/plain; charset=utf-8
4Content-Length: 12
5
6Bad Request
7$ curl -i -d "This is not XML" localhost:3000
8HTTP/1.1 415 Unsupported Media Type
9Content-Type: text/plain; charset=utf-8
10Content-Length: 23
11
12Unsupported Media Type
13$ curl -i -d @books.xml localhost:3000
14HTTP/1.1 200 OK
15Date: Fri, 17 Oct 2014 13:42:10 GMT
16Content-Length: 2
17Content-Type: text/plain; charset=utf-8
18
19OK
使用第三方中间件
有时你可能想用第三方的包,而不是一直使用自己写的中间件。我们来看看两个例子:goji/httpauth 和 LoggingHandler。
goji/httpauth 包提供 HTTP 基本身份验证功能。它有一个叫SimpleBasicAuth
的辅助函数,它返回一个带有func(http.Handler) http.Handler
签名的函数。这意味着我们可以像用自定义中间件完全相同的方式来使用它。
1$ go get github.com/goji/httpauth
File: main.go
1package main
2
3import (
4 "github.com/goji/httpauth"
5 "net/http"
6)
7
8func main() {
9 finalHandler := http.HandlerFunc(final)
10 authHandler := httpauth.SimpleBasicAuth("username", "password")
11
12 http.Handle("/", authHandler(finalHandler))
13 http.ListenAndServe(":3000", nil)
14}
15
16func final(w http.ResponseWriter, r *http.Request) {
17 w.Write([]byte("OK"))
18}
如果你运行这个例子,你将会得到一个有效凭证和无效凭证的预期响应:
1$ curl -i username:password@localhost:3000
2HTTP/1.1 200 OK
3Content-Length: 2
4Content-Type: text/plain; charset=utf-8
5
6OK
7$ curl -i username:wrongpassword@localhost:3000
8HTTP/1.1 401 Unauthorized
9Content-Type: text/plain; charset=utf-8
10Www-Authenticate: Basic realm=""Restricted""
11Content-Length: 13
12
13Unauthorized
Gorilla 的LoggingHandler
- 记录了Apache 风格的日志 - 这个中间件跟之前的会有一点不同。
它使用签名func(out io.Writer, h http.Handler) http.Handler
,因此它不仅需要下一个处理程序的参数,还需要用来写入日志的io.Writer的参数。
下面这个简单的例子,我们将日志写入 server.log 文件:
1go get github.com/gorilla/handlers
File: main.go
1package main
2
3import (
4 "github.com/gorilla/handlers"
5 "net/http"
6 "os"
7)
8
9func main() {
10 finalHandler := http.HandlerFunc(final)
11
12 logFile, err := os.OpenFile("server.log", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
13 if err != nil {
14 panic(err)
15 }
16
17 http.Handle("/", handlers.LoggingHandler(logFile, finalHandler))
18 http.ListenAndServe(":3000", nil)
19}
20
21func final(w http.ResponseWriter, r *http.Request) {
22 w.Write([]byte("OK"))
23}
在这样一个简单的例子中,我们的代码相当清楚。但是,如果我们想将LoggingHandler
作为更长的中间件调用链的一部分,会发生什么?我们很容易想到一个看起来像这样的声明……
1http.Handle("/", handlers.LoggingHandler(logFile, authHandler(enforceXMLHandler(finalHandler))))
……这种方式真是让我很头疼!
一种让它更清晰的方法是使用签名func(http.Handler) http.Handler
来创建一个构造函数(命名为myLoggingHandler
)。这会使得它与其他中间件的嵌套更整洁:
1func myLoggingHandler(h http.Handler) http.Handler {
2 logFile, err := os.OpenFile("server.log", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
3 if err != nil {
4 panic(err)
5 }
6 return handlers.LoggingHandler(logFile, h)
7}
8
9func main() {
10 finalHandler := http.HandlerFunc(final)
11
12 http.Handle("/", myLoggingHandler(finalHandler))
13 http.ListenAndServe(":3000", nil)
14}
如果你运行此应用并发送一些请求给它,你的server.log
文件应如下所示:
1$ cat server.log
2127.0.0.1 - - [21/Oct/2014:18:56:43 +0100] "GET / HTTP/1.1" 200 2
3127.0.0.1 - - [21/Oct/2014:18:56:36 +0100] "POST / HTTP/1.1" 200 2
4127.0.0.1 - - [21/Oct/2014:18:56:43 +0100] "PUT / HTTP/1.1" 200 2
如果你有兴趣,这里给出一个把该文章的3 个中间件处理函数结合在一个例子中的 gist 仓库。
边注:注意Gorilla LoggingHandler
正在记录日志中的响应状态(200
)和响应长度(2
)。这比较有趣,上游日志记录中间件怎么获取了应用处理程序写入的响应体的信息?
它通过定义自己的responseLogger
类型来实现这一点,该类型封装了http.ResponseWriter
,并创建自定义responseLogger.Write()
和responseLogger.WriteHeader()
方法。这些方法不仅可以写入响应,还可以存储响应的大小和状态以供后面检查。 Gorilla 的LoggingHandler
将responseLogger
传递给链中的下一个处理程序,取代了普通的http.ResponseWriter
。
额外的工具
Alice by Justinas Stankevičius是一个巧妙且非常轻量级的包,为链式中间件处理程序提供了一些语法糖。最基本的 Alice 包可以让你重新下面的代码:
1http.Handle("/", myLoggingHandler(authHandler(enforceXMLHandler(finalHandler))))
变为:
1http.Handle("/", alice.New(myLoggingHandler, authHandler, enforceXMLHandler).Then(finalHandler))
至少在我看来,瞥一眼这个代码就能让人大致理解了。但是,Alice 包的真正好处是只需要指定一次处理链,并能将其重用于多个路由当中。像这样:
1stdChain := alice.New(myLoggingHandler, authHandler, enforceXMLHandler)
2
3http.Handle("/foo", stdChain.Then(fooHandler))
4http.Handle("/bar", stdChain.Then(barHandler))
如果你喜欢这篇博文,请不要忘记查看我的新书《用 Go 构建专业的 Web 应用程序》
在推特上关注我 @ajmedwards
此文章中的所有代码都可以在MIT Licence许可下免费使用。