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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68 import std/[asyncdispatch, asynchttpserver]
import std/nativesockets
import std/[json, parseutils, strutils]
import std/os
import threadvars, types, utils, requestHandler
proc main {.async.} =
proc CtrlCHook() {.noconv.} =
echo "Ctrl+C fired! \nStopping Server now!"
quit()
proc callback(req: Request) {.async.} =
await requestHandler(req)
try:
setControlCHook(CtrlCHook)
var configPath = "/var/lib/travelynx2fedi/config.ini"
storagePath = "/var/lib/travelynx2fedi"
if existsEnv("TRAVELYNX2FEDI_STORAGE_PATH"):
storagePath = getEnv("TRAVELYNX2FEDI_STORAGE_PATH")
if existsEnv("TRAVELYNX2FEDI_CONFIG_PATH"):
configPath = getEnv("TRAVELYNX2FEDI_CONFIG_PATH")
if not dirExists(storagePath):
echo "The storage path '" & storagePath & "' doesn't exist!"
quit(1)
if not fileExists(configPath):
echo "The config file '" & configPath & "' doesn't exist!"
quit(1)
if not fileExists(storagePath & "/state.json"):
writeFile(storagePath & "/state.json", "{}")
config = parseConfig(configPath)
state = parseFile(storagePath & "/state.json")
let server = newAsyncHttpServer()
var port = config.ServerPort
if existsEnv("TRAVELYNX2FEDI_PORT"):
port = Port(getEnv("TRAVELYNX2FEDI_PORT").parseInt)
server.listen(Port(port), "::1", AF_INET6)
echo "Started webserver on port " & $server.getPort
while true:
if server.shouldAcceptRequest():
await server.acceptRequest(callback)
else:
await sleepAsync(500)
except:
let
e = getCurrentException()
msg = getCurrentExceptionMsg()
echo "Got exception ", repr(e), " with message ", msg
echo "error happend, meh."
quit(1)
waitFor main()