Last active
May 28, 2024 18:39
-
-
Save treeform/a436737704564b2bed892a626acc2cd4 to your computer and use it in GitHub Desktop.
genWeekEtag
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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