OxL Справочник OxL
РусскийEnglish

module std.web

std.web — static sites for std.http (II.4 std.web, D-7884..D-7889): a site embedded in the program with comptime.embedDir.

oxl
use std.http { Server, ServerConfig, Router, Request, Reply }
use std.web { Site, cacheRule }

static SITE: Site = Site.embedded(comptime.embedDir("build/site"),
                                  [cacheRule("assets/*", "public, max-age=31536000, immutable"), cacheRule("*.html", "no-cache")])

fn page(req: Request) -> Reply => SITE.reply(req)

fn main() -> () | NetError  net, io, time {
  let srv = Server.bind(ServerConfig{ port: 8080 })?
  srv.serve(Router.new().get("/", page).get("/*rest", page))?
}
  • comptime.embedDir(path) puts the files of a directory into the binary; each one is stored gzip-compressed at build time, with a content hash as ETag (a List<(str, str, str, bytes, i64)>: path, media type, ETag, gzip data, size).
  • Site.reply answers GET and HEAD (other methods: 405): / and /dir/ give index.html, /dir redirects to /dir/ when it is a directory, .. and hidden paths give 404 (served from 404.html when the site has one), there is no directory listing.
  • ETag and If-None-Match (304 Not Modified); Cache-Control by the first matching cacheRule (a glob with one *), default public, max-age=300; Vary: Accept-Encoding; the stored gzip data is sent as it is (Content-Encoding: gzip) to clients that accept it and inflated for the others. Security headers: X-Content-Type-Options: nosniff, Referrer-Policy: no-referrer.
  • Not implemented in this version (the Standard lists them): Range, StaticFs.dir (files from disk), .br files, templates, the other middleware of II.4.

Example:

oxl✓ проверяется в CI
use std.web { Site, cacheRule }
use std.http { Request }

fn main() io {
  let gz = b"\x1f\x8b\x08\x00\x00\x00\x00\x00\x02\xff\xcb\x48\xcd\xc9\xc9\x07\x00\x86\xa6\x10\x36\x05\x00\x00\x00"
  let site = Site.embedded([("index.html", "text/html", "\"v1\"", gz, 5)], [cacheRule("*.html", "no-cache")])
  let req = Request{ method: "GET", target: "/", path: "/", rawQuery: "", version: "HTTP/1.1", headers: [], body: Utf8.encode(""), peer: "", params: [] }
  print("{site.count()} {site.reply(req).status}")
}
Вывод
1 200

Типы

data CacheRuleCache-Control for the paths that match pattern
data SiteA site held in memory.

Функции

cacheRuleA Cache-Control rule

См. также