Url Parsing in Elixir
Here’s the translation of the URL parsing example from Go to Elixir, formatted for Hugo:
This Elixir code demonstrates URL parsing using the built-in URI
module. Here’s a breakdown of the translation:
We define a module
UrlParsing
with amain
function.The example URL string remains the same.
We use
URI.parse/1
to parse the URL string into aURI
struct.We use pattern matching to ensure the URL was parsed successfully.
Accessing the scheme, userinfo, host, path, and fragment is done directly through the struct fields.
For splitting the userinfo into username and password, we use
String.split/2
.The
URI
struct provides separatehostname
andport
fields, so we don’t need to split them manually.Query parameters are accessed through the
query
field. We useURI.decode_query/1
to parse them into a map.We use
IO.puts/1
andIO.inspect/1
for output, which are roughly equivalent tofmt.Println
in Go.
Running this Elixir program will show all the different pieces extracted from the URL, similar to the Go version:
This example demonstrates how to parse and extract information from URLs in Elixir, covering scheme, authentication, host, port, path, query parameters, and fragments.