返回介绍

Middleware

发布于 2025-02-25 22:26:26 字数 1790 浏览 0 评论 0 收藏 0

If you have some code that needs to be run for every request, regardless of the route that it will eventually end up invoking, you need some way to stack http.Handlers on top of each other and run them in sequence. This problem is solved elegantly through middleware packages. Negroni is a popular middleware package that makes building and stacking middleware very easy while keeping the composable nature of the Go web ecosystem intact.

Negroni comes with some default middleware such as Logging, Error Recovery, and Static file serving. So out of the box Negroni will provide you with a lot of value without a lot of overhead.

The example below shows how to use a Negroni stack with the built in middleware and how to create your own custom middleware.

package main

import (
  "log"
  "net/http"

  "github.com/codegangsta/negroni"
)

func main() {
  // Middleware stack
  n := negroni.New(
    negroni.NewRecovery(),
    negroni.HandlerFunc(MyMiddleware),
    negroni.NewLogger(),
    negroni.NewStatic(http.Dir("public")),
  )

  n.Run(":8080")
}

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)
  } else {
    http.Error(rw, "Not Authorized", 401)
  }

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

Exercises

  1. Think of some cool middleware ideas and try to implement them using Negroni.
  2. Explore how Negroni can be composed with github.com/gorilla/mux using the http.Handler interface.
  3. Play with creating Negroni stacks for certain groups of routes instead of the entire application.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文