Product
Introducing License Enforcement in Socket
Ensure open-source compliance with Socket’s License Enforcement Beta. Set up your License Policy and secure your software!
github.com/justinas/alice
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 different 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/throttled/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. Once it passes the execution to the outer layer of middleware, it has no saying in whether middleware will execute the inner handlers. This is intentional behavior.
Alice works with Go 1.0 and higher.
FAQs
Unknown package
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Product
Ensure open-source compliance with Socket’s License Enforcement Beta. Set up your License Policy and secure your software!
Product
We're launching a new set of license analysis and compliance features for analyzing, managing, and complying with licenses across a range of supported languages and ecosystems.
Product
We're excited to introduce Socket Optimize, a powerful CLI command to secure open source dependencies with tested, optimized package overrides.