Joining URI parts in Elixir
Elixir 1.3 introduced a standard way to join URIs.
For example, say we have a base URI for an API: https://api.hashrocket.com
and different endpoints on that URI: events
, developers
, applications
.
To join the URI into one properly formatted string:
def endpoint_uri(endpoint) do
"https://api.hashrocket.com"
|> URI.merge(endpoint)
|> URI.to_string()
end
# then call it
endpoint_url("events") # => "https://api.hashrocket.com/events"
URI.merge
accepts both strings and URI structs as the first object so you can easily continue adding URI parts to the pipeline including query params:
"https://test.com"
|> URI.merge("events")
|> URI.merge("?date=today")
|> URI.to_string()
# => "https://test.com/events?date=today"
Tweet