查看 Negroni 中间件。它让您通过不同的中间件和自定义 HandlerFuncs 传递您的 HTTP 请求。像这样的东西:


   n := negroni.New(

        negroni.NewRecovery(),

        negroni.HandlerFunc(myMiddleware),

        negroni.NewLogger(),

        negroni.NewStatic(http.Dir("public")),

    )


...

...


func myMiddleware(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {

    log.Println("Logging on the way there...")


    if r.URL.Query().Get("password") == "secret123" {

        next(rw, r)      //**<--------passing the request to next middleware/func**

    } else {

        http.Error(rw, "Not Authorized", 401)

    }


    log.Println("Logging on the way back...")

}

注意如何next(rw,r)用于传递 HTTP 请求


如果您不想使用 Negroni,您可以随时查看它的实现,了解它如何将 HTTP 请求传递给另一个中间件。


它使用自定义处理程序,看起来像:


handlerFunc func(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc)

参考:https : //gobridge.gitbooks.io/building-web-apps-with-go/content/en/middleware/index.html