Url Parsing in Elixir

Here’s the translation of the URL parsing example from Go to Elixir, formatted for Hugo:

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

    # Parse the URL and ensure there are no errors.
    case URI.parse(s) do
      %URI{} = u ->
        # Accessing the scheme is straightforward.
        IO.puts(u.scheme)

        # User contains all authentication info; we can extract
        # username and password separately.
        IO.puts("#{u.userinfo}")
        [username, password] = String.split(u.userinfo, ":")
        IO.puts(username)
        IO.puts(password)

        # The Host contains both the hostname and the port,
        # if present. We can extract them separately.
        IO.puts(u.host)
        IO.puts(u.hostname)
        IO.puts(u.port)

        # Here we extract the path and the fragment after
        # the #.
        IO.puts(u.path)
        IO.puts(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 map.
        IO.puts(u.query)
        query_params = URI.decode_query(u.query)
        IO.inspect(query_params)
        IO.puts(query_params["k"])

      _ ->
        IO.puts("Failed to parse URL")
    end
  end
end

UrlParsing.main()

This Elixir code demonstrates URL parsing using the built-in URI module. Here’s a breakdown of the translation:

  1. We define a module UrlParsing with a main function.

  2. The example URL string remains the same.

  3. We use URI.parse/1 to parse the URL string into a URI struct.

  4. We use pattern matching to ensure the URL was parsed successfully.

  5. Accessing the scheme, userinfo, host, path, and fragment is done directly through the struct fields.

  6. For splitting the userinfo into username and password, we use String.split/2.

  7. The URI struct provides separate hostname and port fields, so we don’t need to split them manually.

  8. Query parameters are accessed through the query field. We use URI.decode_query/1 to parse them into a map.

  9. We use IO.puts/1 and IO.inspect/1 for output, which are roughly equivalent to fmt.Println in Go.

Running this Elixir program will show all the different pieces extracted from the URL, similar to the Go version:

$ elixir url_parsing.exs
postgres
user:pass
user
pass
host.com:5432
host.com
5432
/path
f
k=v
%{"k" => "v"}
v

This example demonstrates how to parse and extract information from URLs in Elixir, covering scheme, authentication, host, port, path, query parameters, and fragments.