Skip to content

Instantly share code, notes, and snippets.

@treeform
Last active May 28, 2024 18:39
Show Gist options
  • Save treeform/a436737704564b2bed892a626acc2cd4 to your computer and use it in GitHub Desktop.
Save treeform/a436737704564b2bed892a626acc2cd4 to your computer and use it in GitHub Desktop.
genWeekEtag
proc genWeekEtag*(filepath: string): string =
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag
let
info = getFileInfo(filepath)
ns = info.lastWriteTime.toUnix().uint64 * 1e9.uint64 + info.lastWriteTime.nanosecond.uint64
time = toHex(ns, sizeof(uint64)).toLowerAscii()
size = toHex(info.size, sizeof(uint64)).toLowerAscii()
result = "W/" & '"' & size & '-' & time & '"'
proc serveFile*(req: Request, path: string) {.async.} =
let etag = genWeekEtag(path)
if req.headers.hasKey("If-None-Match") and req.headers["If-None-Match"] == etag:
await req.respond(Http304, "")
else:
let data = readFile(path)
let headers = newHttpHeaders()
headers["Content-Type"] = mimeType(path)
headers["ETag"] = etag
await req.respond(
Http200,
data,
headers,
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment