围绕Handler接口的方法ServeHTTP,可以轻松的写出go中的中间件

0 429
索鸟 2021-01-20
需要:0索币

 Golang标准库http包提供了基础的http服务,这个服务又基于Handler接口和ServeMux结构的叫做Mutilpexer。实际上,go的作者设计Handler这样的接口,不仅提供了默认的ServeMux对象,开发者也可以自定义ServeMux对象。

    本质上ServeMux只是一个路由管理器,而它本身也实现了Handler接口的ServeHTTP方法。因此围绕Handler接口的方法ServeHTTP,可以轻松的写出go中的中间件。

自定义的Handler

    标准库http提供了Handler接口,用于开发者实现自己的handler。只要实现接口的ServeHTTP方法即可。

  1. type textHandler struct {
  2. responseText string
  3. }
  4. func (th *textHandler) ServeHTTP(w http.ResponseWriter, r *http.Request){
  5. fmt.Fprintf(w, th.responseText)
  6. }
  7. type indexHandler struct {}
  8. func (ih *indexHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  9. w.Header().Set("Content-Type", "text/html")
  10. html := `<doctype html>
  11. <html>
  12. <head>
  13. <title>Hello World</title>
  14. </head>
  15. <body>
  16. <p>
  17. <a href="/welcome">Welcome</a> | <a href="/message">Message</a>
  18. </p>
  19. </body>
  20. </html>`
  21. fmt.Fprintln(w, html)
  22. }
  23. func main() {
  24. mux := http.NewServeMux()
  25. mux.Handle("/", &indexHandler{})
  26. thWelcome := &textHandler{"TextHandler !"}
  27. mux.Handle("/text",thWelcome)
  28. http.ListenAndServe(":8000", mux)
  29. }

   上面自定义了两个handler结构,都实现了ServeHTTP方法。我们知道,NewServeMux可以创建一个ServeMux实例,ServeMux同时也实现了ServeHTTP方法,因此代码中的mux也是一种handler。把它当作参数传给http.ListenAndServe方法,后者会把mux传给Server实例。因为指定了handler,因此整个http服务就不再是DefaultServeMux,而是mux,无论是在注册路由还是提供请求服务的时候。

 

   有一点值得注意,这里并没有使用HandleFunc注册路由,而是直接使用了mux注册路由。当没有指定mux的时候,系统需要创建一个默认的defaultServeMux,此时我们已经有了mux,因此不需要http.HandleFunc方法了,直接使用mux的Handle方法注册即可。

   此外,Handle第二个参数是一个Handler(处理器),并不是HandleFunc的一个handler函数,其原因是mux.Handle本质上就需要绑定url的pattern模式和handler(处理器)即可。既然indexHandler是handle(处理器),当然就能作为参数,一切请求的处理过程,都交给实现的接口方法ServeHTTP就行了。
  

创建Handler处理器

  1. func text(w http.ResponseWriter, r *http.Request){
  2. fmt.Fprintln(w, "hello world")
  3. }
  4. func index(w http.ResponseWriter, r *http.Request) {
  5. w.Header().Set("Content-Type", "text/html")
  6. html := `<doctype html>
  7. <html>
  8. <head>
  9. <title>Hello World</title>
  10. </head>
  11. <body>
  12. <p>
  13. <a href="/welcome">Welcome</a> | <a href="/message">Message</a>
  14. </p>
  15. </body>
  16. </html>`
  17. fmt.Fprintln(w, html)
  18. }
  19. func main() {
  20. mux := http.NewServeMux()
  21. mux.Handle("/", http.HandlerFunc(index))
  22. mux.HandleFunc("/text", text)
  23. http.ListenAndServe(":8000", mux)
  24. }

   代码中使用了http.HandlerFunc方法直接将一个handler函数转变成实现了handler(处理器)。
 

 

使用默认的DefaultServeMux

  1. func main() {
  2. http.Handle("/", http.HandlerFunc(index))
  3. http.HandleFunc("/text", text)
  4. http.ListenAndServe(":8000", nil)
  5. }

   当代码中不显示的创建serveMux对象,http包就默认创建一个DefaultServeMux对象用来做路由管理器mutilplexer。
 

 

自定义Server

   默认的DefaultServeMux创建的判断来自server对象,如果server对象不提供handler,才会使用默认的serveMux对象。既然ServeMux可以自定义,那么Server对象一样可以。

   使用http.Server即可创建自定义的server对象:

  1. func main(){
  2. http.HandleFunc("/", index)
  3. server := &http.Server{
  4. Addr: ":8000",
  5. ReadTimeout: 60 * time.Second,
  6. WriteTimeout: 60 * time.Second,
  7. }
  8. server.ListenAndServe()
  9. }

   自定义的serverMux对象也可以传到server对象中。

  1. func main() {
  2. mux := http.NewServeMux()
  3. mux.HandleFunc("/", index)
  4. server := &http.Server{
  5. Addr: ":8000",
  6. ReadTimeout: 60 * time.Second,
  7. WriteTimeout: 60 * time.Second,
  8. Handler: mux,
  9. }
  10. server.ListenAndServe()
  11. }

   可见go中的路由和处理函数之间关系非常密切,同时又很灵活。

 

中间件Middleware

   中间件就是连接上下级不同功能的函数或软件,通常进行一些包裹函数的行为,为被包裹函数提供一些功能或行为。

   go的http中间件很简单,只要实现一个函数签名为func(http.Handler) http.Handler的函数即可。http.Handler是一个接口,接口方法我们熟悉的为serveHTTP。返回也是一个handler。因为go中的函数也可以当作变量传递或者返回,只要这个函数是一个handler即可,即实现或被handlerFunc包裹成handler处理器。

  1. func middlewareHandler(next http.Handler) http.Handler{
  2. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request){
  3. // 执行handler之前的逻辑
  4. next.ServeHTTP(w, r)
  5. // 执行完毕handler后的逻辑
  6. })
  7. }


   go的实现实例:

  1. func loggingHandler(next http.Handler) http.Handler {
  2. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  3. start := time.Now()
  4. log.Printf("Started %s %s", r.Method, r.URL.Path)
  5. next.ServeHTTP(w, r)
  6. log.Printf("Comleted %s in %v", r.URL.Path, time.Since(start))
  7. })
  8. }
  9. func main() {
  10. http.Handle("/", loggingHandler(http.HandlerFunc(index)))
  11. http.ListenAndServe(":8000", nil)
  12. }

   既然中间件是一种函数,并且签名都是一样,那么很容易就联想到函数一层包一层的中间件。再添加一个函数,然后修改main函数:

  1. func hook(next http.Handler) http.Handler{
  2. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  3. log.Println("before hook")
  4. next.ServeHTTP(w, r)
  5. log.Println("after hook")
  6. })
  7. }
  8. func main() {
  9. http.Handle("/", hook(loggingHandler(http.HandlerFunc(index))))
  10. http.ListenAndServe(":8000", nil)
  11. }

   函数调用形成一条链,可以在这条链上做很多事情。
 

参考:

https://www.yuque.com/docs/share/c03cf792-227a-4e7a-850b-4789e479361d

回帖
  • 消灭零回复
相关主题
2020年最新最新Kubernetes视频教程(K8s)教程 2
程序员转型之制作网课变现,月入过万告别996 1
索鸟快传2.0发布啦 1
两个不同网络的电脑怎么实现文件的互相访问呢? 1
网盘多账号登录软件 1
Java实战闲云旅游项目基于vue+element-ui 1
单点登录技术解决方案基于OAuth2.0的网关鉴权RSA算法生成令牌 1
QT5获取剪贴板上文本信息QT设置剪贴板内容 1
springboot2实战在线购物系统电商系统 1
python web实战之爱家租房项目 1
windows COM实用入门教程 1
C++游戏开发之C++实现的水果忍者游戏 1
计算机视觉库opencv教程 1
node.js实战图书管理系统express框架实现 1
C++实战教程之远程桌面远程控制实战 1
相关主题
PHP7报A non well formed numeric value encountered 0
Linux系统下关闭mongodb的几种命令分享 0
mongodb删除数据、删除集合、删除数据库的命令 0
Git&Github极速入门与攻坚实战课程 0
python爬虫教程使用Django和scrapy实现 0
libnetsnmpmibs.so.31: cannot open shared object file 0
数据结构和算法视频教程 0
redis的hash结构怎么删除数据呢? 0
C++和LUA解析器的数据交互实战视频 0
mongodb errmsg" : "too many users are authenticated 0
C++基础入门视频教程 0
用30个小时精通C++视频教程可能吗? 0
C++分布式多线程游戏服务器开发视频教程socket tcp boost库 0
C++培训教程就业班教程 0
layui的util工具格式时间戳为字符串 0
C++实战教程之远程桌面远程控制实战 1
网络安全培训视频教程 0
LINUX_C++软件工程师视频教程高级项目实战 0
C++高级数据结构与算法视频教程 0
跨域问题很头疼?通过配置nginx轻松解决ajax跨域问题 0