Prevent overwriting, allow deletion.
This commit is contained in:
Binary file not shown.
@ -11,22 +11,25 @@ type
|
||||
port*: int
|
||||
urls*: StringTableRef
|
||||
|
||||
const CT_TXT = "text/plain"
|
||||
|
||||
proc parseUrlLine(line: string, lineNo: int): tuple[k, v: string] =
|
||||
let pair = line.split("\t")
|
||||
if pair.len != 2:
|
||||
warn "Error loading URLs file. Line #" & $lineNo &
|
||||
" does not contain exactly two values separated by \\t."
|
||||
raise newException(ValueError, "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()
|
||||
|
||||
var lineNo = 0
|
||||
for line in filename.lines:
|
||||
lineNo += 1
|
||||
let pair = parseUrlLine(line, lineNo)
|
||||
result[pair.k] = pair.v
|
||||
debug "Adding: " & pair.k & " -> " & pair.v
|
||||
if fileExists(filename):
|
||||
var lineNo = 0
|
||||
for line in filename.lines:
|
||||
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
|
||||
@ -87,7 +90,7 @@ proc serveApi(cfg: ToClerbeCfg) =
|
||||
routes:
|
||||
|
||||
options "version": sendOptionsResp(@[HttpGet])
|
||||
get "version": resp "to.cler.be v" & TOCLERBE_VERSION
|
||||
get "version": resp("to.cler.be v" & TOCLERBE_VERSION, CT_TXT)
|
||||
|
||||
options "api/create": sendOptionsResp(@[HttpPost])
|
||||
post "api/create":
|
||||
@ -97,19 +100,35 @@ proc serveApi(cfg: ToClerbeCfg) =
|
||||
for line in request.body.splitLines:
|
||||
lineNo += 1
|
||||
let pair = parseUrlLine(line, lineNo)
|
||||
if cfg.urls.contains(pair.k):
|
||||
halt(Http403, {"Content-Type": CT_TXT},
|
||||
"mapping already exists for " & pair.k)
|
||||
|
||||
cfg.urls[pair.k] = pair.v
|
||||
info "Added URL mapping: " & pair.k & " -> " & pair.v
|
||||
cfg.persist()
|
||||
resp(Http200, "", "text/plain")
|
||||
except:
|
||||
resp(Http500, {"Content-Type": "text/plain"}, getCurrentExceptionMsg())
|
||||
resp(Http200, "", CT_TXT)
|
||||
|
||||
except:
|
||||
resp(Http500, getCurrentExceptionMsg(), CT_TXT)
|
||||
|
||||
options re".*": sendOptionsResp(@[HttpGet, HttpDelete])
|
||||
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, {"Content-Type": "text/plain"}, "not found")
|
||||
resp(Http404, "not found", CT_TXT)
|
||||
|
||||
delete re".*":
|
||||
checkAuth(cfg)
|
||||
try:
|
||||
cfg.urls.del(request.pathInfo)
|
||||
cfg.persist()
|
||||
resp(Http200, "", CT_TXT)
|
||||
|
||||
except:
|
||||
resp(Http500, getCurrentExceptionMsg(), CT_TXT)
|
||||
|
||||
when isMainModule:
|
||||
|
||||
|
Reference in New Issue
Block a user