Fix URL parsing, erorr handling, URL matching.
This commit is contained in:
parent
8c3f48a0f3
commit
e77e999fcb
2
.gitignore
vendored
Normal file
2
.gitignore
vendored
Normal file
@ -0,0 +1,2 @@
|
||||
.*.sw?
|
||||
toclerbe
|
Binary file not shown.
@ -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>"],
|
||||
|
@ -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
|
||||
|
Loading…
x
Reference in New Issue
Block a user