Composable handler -> handler middleware for the pure SML HTTP core. A
handler is request -> response (sml-http's model); middlewares wrap handlers
and stack with ordinary composition. Everything is pure and deterministic —
logs accumulate in a caller-owned sink and static files are served from an
in-memory map, not the OS. Dual-compiler: MLton + Poly/ML.
compose— stack middlewares left-to-right (compose [a, b] h = a (b h)), first listed wraps outermost.catchErrors— turn a raising handler into a response (e.g. a 500).limitBody— reject oversized request bodies with413 Payload Too Large.logTo— append a formatted log line per request to astring list ref.addHeader— set a response header on every response (e.g. security headers).static— serveGET/HEADfrom an in-memory file map; keys match by exact path or sml-glob pattern, otherwise the request falls through to the inner handler.
type handler = Http.request -> Http.response
type middleware = handler -> handler
val compose : middleware list -> middleware
val catchErrors : (exn -> Http.response) -> middleware
val limitBody : int -> middleware
val logTo : string list ref -> (Http.request * Http.response -> string) -> middleware
val addHeader : string -> string -> middleware
val static : (string * (string * string)) list -> middlewareval app =
Middleware.compose
[ Middleware.logTo sink fmt
, Middleware.catchErrors (fn _ => Http.text 500 "Internal Error")
, Middleware.addHeader "X-Powered-By" "sml-web"
, Middleware.static [("/", ("text/html", "<h1>Welcome</h1>")),
("/static/*", ("text/plain", "asset"))] ]
(fn _ => Http.text 404 "Not Found")
val res = app someRequestRun the bundled example (over hand-built requests):
make examplemake test # MLton
make test-poly # Poly/ML
make all-tests # both20 deterministic checks, identical under MLton and Poly/ML.
package github.com/sjqtentacles/sml-middleware
require {
github.com/sjqtentacles/sml-http
github.com/sjqtentacles/sml-glob
}
Dependencies are also vendored under lib/github.com/sjqtentacles/ and
committed, so make needs no network.
lib/github.com/sjqtentacles/sml-middleware/
middleware.sig middleware.sml
sources.mlb sml-middleware.mlb
examples/app.sml stacked example app
test/ Harness suite (20 checks)
MIT