commit | 21d2055946fe276516d0b449603967c9fc95d770 | [log] [tgz] |
---|---|---|
author | Christoffer Hallas <hallas@users.noreply.github.com> | Sat Oct 04 13:26:36 2014 -0400 |
committer | Christoffer Hallas <hallas@users.noreply.github.com> | Sat Oct 04 13:26:36 2014 -0400 |
tree | 6ae6b230c3bd3b7a82bf389364031d2bc297cb37 | |
parent | 35b479054b26b5ba66f85862c85ca90e098c04fe [diff] |
Update README.md Updated README.md to correctly reflect the nature of the middleware. Sequentially means that they're run in sequence, not concurrently, which is also how you describe it in your documentation as excerpted below. // When the request comes in, it will be passed to m1, then m2, then m3 // and finally, the given handler
Alice provides a convenient way to chain your HTTP middleware functions and the app handler.
In short, it transforms
Middleware1(Middleware2(Middleware3(App)))
to
alice.New(Middleware1, Middleware2, Middleware3).Then(App).
None of the other middleware chaining solutions behaves exactly like Alice. Alice is as minimal as it gets: in essence, it's just a for loop that does the wrapping for you.
Check out this blog post for explanation how Alice is diferrent from other chaining solutions.
Your middleware constructors should have the form of
func (http.Handler) http.Handler
Some middleware provide this out of the box. For ones that don‘t, it’s trivial to write one yourself.
func myStripPrefix(h http.Handler) http.Handler {
return http.StripPrefix("/old", h)
}
This complete example shows the full power of Alice.
package main
import (
"net/http"
"time"
"github.com/PuerkitoBio/throttled"
"github.com/justinas/alice"
"github.com/justinas/nosurf"
)
func timeoutHandler(h http.Handler) http.Handler {
return http.TimeoutHandler(h, 1*time.Second, "timed out")
}
func myApp(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello world!"))
}
func main() {
th := throttled.Interval(throttled.PerSec(10), 1, &throttled.VaryBy{Path: true}, 50)
myHandler := http.HandlerFunc(myApp)
chain := alice.New(th.Throttle, timeoutHandler, nosurf.NewPure).Then(myHandler)
http.ListenAndServe(":8000", chain)
}
Here, the request will pass throttled first, then an http.TimeoutHandler we've set up, then nosurf and will finally reach our handler.
Note that Alice makes no guarantees for how one or another piece of middleware will behave. It executes all middleware sequentially so that if a piece of middleware were to stop the chain, the request will not reach the inner handlers. This is intentional behavior.
Alice works with Go 1.0 and higher, but running tests requires at least Go 1.1.
develop
branch, commit, test.