Overview
Chain HTTP-style middleware in Go: functions that take a handler and return a wrapped one, applied so the first middleware in the list runs first.
- a middleware takes and returns a handler
- functions as types: type Handler func
- wrap in reverse so the first runs first
Short Course
A middleware takes a handler and returns a new one that wraps it, to add logging, auth or compression. Trap: wrapping in a loop from first to last makes the last middleware the outermost; wrap in reverse so the first runs first.
type Handler func(req string) string
func Log(next Handler) Handler {
return func(req string) string {
return "log(" + next(req) + ")"
}
}
Task
Write Chain(h Handler, mws ...Middleware) Handler: h wrapped so mws[0]
is the outermost layer. Example: Chain(h, Tag("a"), Tag("b"))("x") →
"a(b(x))", where h returns its input.
Test Suites
Pending
Next
Output