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.
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 asETag(aList<(str, str, str, bytes, i64)>: path, media type, ETag, gzip data, size).Site.replyanswersGETandHEAD(other methods:405):/and/dir/giveindex.html,/dirredirects to/dir/when it is a directory,..and hidden paths give404(served from404.htmlwhen the site has one), there is no directory listing.ETagandIf-None-Match(304 Not Modified);Cache-Controlby the first matchingcacheRule(a glob with one*), defaultpublic, 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),.brfiles, templates, the other middleware of II.4.
Example:
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}")
}Output
1 200
Types
Functions
cacheRule | A Cache-Control rule |