ctucx.git: oeffisearch

[nimlang] fast and simple tripplanner

1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
27 
28 
29 
30 
31 
32 
33 
34 
35 
36 
37 
38 
# 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)
  if path.fileExists:
    return sendStaticFile(path)
  if fileExists(path & "index.html"):
    return sendStaticFile(path & "index.html")
  else:
    raise newException(notFoundException, "NOT_FOUND")