# Middleware
If you have some code that needs to be run for every request, regardless ofthe 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 issolved elegantly through middleware packages. Negroni is a popular middlewarepackage that makes building and stacking middleware very easy while keeping thecomposable nature of the Go web ecosystem intact.
Negroni comes with some default middleware such as Logging, Error Recovery, andStatic file serving. So out of the box Negroni will provide you with a lot ofvalue without a lot of overhead.
The example below shows how to use a Negroni stack with the built in middlewareand 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.
1. Explore how Negroni can be composed with `github.com/gorilla/mux` using the `http.Handler` interface.
1. Play with creating Negroni stacks for certain groups of routes instead of the entire application.
- Introduction
- 1. Go Makes Things Simple
- 2. The net/http package
- 3. Creating a Basic Web App
- 4. Deployment
- 5. URL Routing
- 6. Middleware
- 7. Rendering
- JSON
- HTML Templates
- Using The render package
- 8. Testing
- Unit Testing
- End to End Testing
- 9. Controllers
- 10. Databases
- 11. Tips and Tricks
- 12. Moving Forward