Fix URL parsing, erorr handling, URL matching.

This commit is contained in:
Jonathan Bernard 2023-03-09 23:28:45 -06:00
parent 8c3f48a0f3
commit e77e999fcb
4 changed files with 19 additions and 11 deletions

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
.*.sw?
toclerbe

Binary file not shown.

View File

@ -16,6 +16,7 @@ proc parseUrlLine(line: string, lineNo: int): tuple[k, v: string] =
if pair.len != 2:
warn "Error loading URLs file. Line #" & $lineNo &
" does not contain exactly two values separated by \\t."
result = (pair[0], pair[1])
proc loadUrlsFile(filename: string): StringTableRef =
result = newStringTable()
@ -25,6 +26,7 @@ proc loadUrlsFile(filename: string): StringTableRef =
lineNo += 1
let pair = parseUrlLine(line, lineNo)
result[pair.k] = pair.v
debug "Adding: " & pair.k & " -> " & pair.v
proc persist(cfg: ToClerbeCfg) =
var f: File
@ -84,37 +86,41 @@ proc serveApi(cfg: ToClerbeCfg) =
routes:
options "/version": sendOptionsResp(@[HttpGet])
get "/version": resp "to.cler.be v" & TOCLERBE_VERSION
options "version": sendOptionsResp(@[HttpGet])
get "version": resp "to.cler.be v" & TOCLERBE_VERSION
options "/api/create": sendOptionsResp(@[HttpPost])
post "/api/create":
options "api/create": sendOptionsResp(@[HttpPost])
post "api/create":
checkAuth(cfg)
try:
var lineNo = 0
for line in request.body.lines:
for line in request.body.splitLines:
lineNo += 1
let pair = parseUrlLine(line, lineNo)
cfg.urls[pair.k] = pair.v
info "Added URL mapping: " & pair.k & " -> " & pair.v
cfg.persist()
resp(Http200, "")
resp(Http200, "", "text/plain")
except:
resp(Http500, getCurrentExceptionMsg())
resp(Http500, {"Content-Type": "text/plain"}, getCurrentExceptionMsg())
get re".*":
debug "Look up short-url: " & request.pathInfo
if cfg.urls.contains(request.pathInfo):
resp(Http302, {"Location": cfg.urls[request.pathInfo]}, "")
else: resp(Http404, "")
else:
resp(Http404, {"Content-Type": "text/plain"}, "not found")
when isMainModule:
let doc = USAGE
logging.addHandler(newConsoleLogger(lvlDebug))
let args = docopt(doc, version = TOCLERBE_VERSION)
logging.addHandler(newConsoleLogger(
if args["--debug"]: lvlDebug
else: lvlInfo))
let cfg = ToClerbeCfg(
apiKeys: getEnv("TOCLERBE_API_KEYS").split(";"),
urlFilePath: $args["<urlFile>"],

View File

@ -11,6 +11,6 @@ bin = @["toclerbe"]
# Dependencies
requires "nim >= 1.6.10"
requires @["docopt", "jester"]
requires @["docopt", "jester", "zero_functional"]
# Dependencies from git.jdb-software.com/nim-packages