Middleware (Basic)

这个例子将展示在Go中创建基本的日志中间件.

这个例子将展示如何在GO中创建基本的日志中间件。一个中间件只需要一个http.HandlerFunc 作为它其中的一个参数,装饰它,并返回一个新的http.HandlerFunc用于服务器调用

  1. // basic-middleware.go
  2. package main
  3. import (
  4. "fmt"
  5. "log"
  6. "net/http"
  7. )
  8. func logging(f http.HandlerFunc) http.HandlerFunc {
  9. return func(w http.ResponseWriter, r *http.Request) {
  10. log.Println(r.URL.Path)
  11. f(w, r)
  12. }
  13. }
  14. func foo(w http.ResponseWriter, r *http.Request) {
  15. fmt.Fprintln(w, "foo")
  16. }
  17. func bar(w http.ResponseWriter, r *http.Request) {
  18. fmt.Fprintln(w, "bar")
  19. }
  20. func main() {
  21. http.HandleFunc("/foo", logging(foo))
  22. http.HandleFunc("/bar", logging(bar))
  23. http.ListenAndServe(":8080", nil)
  24. }
  1. $ go run basic-middleware.go
  2. 2017/02/10 23:59:34 /foo
  3. 2017/02/10 23:59:35 /bar
  4. 2017/02/10 23:59:36 /foo?bar
  5. $ curl -s http://localhost:8080/foo
  6. $ curl -s http://localhost:8080/bar
  7. $ curl -s http://localhost:8080/foo?bar