中间件(基础)

嗨,我是 Philipp!
我想告诉你,我的平台 Go Web 示例课程 刚刚上线。享受关于 Go 中 Web 开发的易于理解的视频课程。一定要查看我为早期支持者提供的特价优惠。
我们会在那里见面的!:)
了解更多

中间件(基础)

此示例将展示如何在 Go 中创建基本的日志记录中间件。

中间件只需将 http.HandlerFunc 作为其参数之一,将其包装起来并返回一个新的 http.HandlerFunc 供服务器调用。

// basic-middleware.go
package main

import (
    "fmt"
    "log"
    "net/http"
)

func logging(f http.HandlerFunc) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        log.Println(r.URL.Path)
        f(w, r)
    }
}

func foo(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "foo")
}

func bar(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "bar")
}

func main() {
    http.HandleFunc("/foo", logging(foo))
    http.HandleFunc("/bar", logging(bar))

    http.ListenAndServe(":8080", nil)
}
$ go run basic-middleware.go
2017/02/10 23:59:34 /foo
2017/02/10 23:59:35 /bar
2017/02/10 23:59:36 /foo?bar

$ curl -s http://localhost:8080/foo
$ curl -s http://localhost:8080/bar
$ curl -s http://localhost:8080/foo?bar