Url Parsing in Lua

Here’s the translation of the Go URL parsing example to Lua, formatted in Markdown suitable for Hugo:

-- We'll parse this example URL, which includes a
-- scheme, authentication info, host, port, path,
-- query params, and query fragment.
local s = "postgres://user:pass@host.com:5432/path?k=v#f"

-- Parse the URL and ensure there are no errors.
local url = require("socket.url")
local u = url.parse(s)
if not u then
    error("Failed to parse URL")
end

-- Accessing the scheme is straightforward.
print(u.scheme)

-- User contains all authentication info; we can access
-- username and password directly.
print(u.user)
print(u.user:match("^([^:]+)"))  -- username
print(u.user:match(":(.+)$"))    -- password

-- The Host contains both the hostname and the port,
-- if present. We can split them manually.
print(u.host)
local host, port = u.host:match("([^:]+):?(%d*)")
print(host)
print(port)

-- Here we extract the path and the fragment after
-- the #.
print(u.path)
print(u.fragment)

-- To get query params in a string of k=v format,
-- use the query field. You can also parse query params
-- into a table.
print(u.query)
local query_params = {}
for k, v in u.query:gmatch("([^&=]+)=([^&=]+)") do
    query_params[k] = v
end
print(require("dkjson").encode(query_params))
print(query_params["k"])

This Lua script demonstrates URL parsing using the socket.url library, which is commonly used for URL manipulation in Lua. Here’s an explanation of the code:

  1. We start by defining the URL string we want to parse.

  2. We use the socket.url library to parse the URL. This library provides functionality similar to Go’s url.Parse().

  3. We then access various components of the parsed URL:

    • The scheme is accessed directly via u.scheme.
    • For user info, we use Lua’s pattern matching to extract username and password.
    • Host and port are extracted using pattern matching as well.
    • Path and fragment are accessed directly.
  4. For query parameters, we access the raw query string and then use a loop with pattern matching to parse it into a table.

  5. Finally, we use the dkjson library to encode the query parameters table to JSON for printing.

To run this program, you would need to have Lua installed along with the luasocket and dkjson libraries. You can typically install these using a package manager like LuaRocks:

$ luarocks install luasocket
$ luarocks install dkjson

Then you can run the script:

$ lua url-parsing.lua

The output would show the different components of the parsed URL, similar to the original example.

Note that Lua doesn’t have built-in URL parsing capabilities as extensive as Go’s, so we use a combination of the socket.url library and manual parsing to achieve similar functionality.