Go · Level 3 Functions

Middleware Chains

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

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) + ")"
    }
}

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.

solution.go
Test Suites Pending
Output