oeffisearch/src/fileserver.nim

39 lines
920 B
Nim
Raw Permalink Normal View History

2020-02-07 14:09:42 +01:00
# inspired by https://github.com/h3rald/nimhttpd
import asynchttpserver
import types
import mimetypes
import uri
import os
import strutils
var mimes {.threadvar.}: MimeDB
proc initFileserver*() =
mimes = newMimeTypes()
proc sendStaticFile(path: string): NimHttpResponse =
var ext = path.splitFile.ext
if ext == "":
ext = ".txt"
ext = ext[1 .. ^1]
let mimetype = mimes.getMimetype(ext.toLowerAscii)
var file = path.readFile
return NimHttpResponse(
code: Http200,
msg: file,
headers: {"Content-Type": mimetype}.newHttpHeaders
)
proc servePath*(req: Request): NimHttpResponse =
let path = "client" & req.url.path.decodeUrl()
#if path.existsDir:
# return sendDirContents(path)
2020-12-04 22:08:31 +01:00
if path.fileExists:
2020-02-07 14:09:42 +01:00
return sendStaticFile(path)
2020-12-04 22:08:31 +01:00
if fileExists(path & "index.html"):
2020-02-07 14:09:42 +01:00
return sendStaticFile(path & "index.html")
else:
raise newException(notFoundException, "NOT_FOUND")