Skip to content

Instantly share code, notes, and snippets.

@ThomasHornschuh
Last active October 20, 2019 09:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ThomasHornschuh/604bf89c0e09d3523125c64b0903645d to your computer and use it in GitHub Desktop.
Save ThomasHornschuh/604bf89c0e09d3523125c64b0903645d to your computer and use it in GitHub Desktop.
Sanitize and parse URL in Lua
function sanitize_url(url)
if url:match("[%s%c]") then
error "url contains spaces or ctrl chars"
end
local proto,tail=url:match('^(%a+)://(.+)')
if not proto then
tail=url
proto="http"
end
local host,colon,port, path_sep,path=tail:match('(^[%a%d-.]+)(:?)(%d*)(/?)([%w%p%?]*)')
if colon==":" and #port==0 then
error "url format: colon without port number"
end
if #path>0 and #path_sep==0 then
error "url format: missing /"
end
if not host then
error "url format: no host"
end
print(string.format("Host=%s Path=%s Port=%s",host,path or "",port or ""))
return {
proto=proto,
host=host,
port=port or "",
path=path or ""
}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment