Skip to content

Commit

Permalink
Ignore params and detect subtype suffix in extensions/1 (#45)
Browse files Browse the repository at this point in the history
* Ignore media type params

* Detect subtype suffix in extensions/1

See: https://tools.ietf.org/html/rfc6838#section-4.2.8
  • Loading branch information
wojtekmach authored Mar 31, 2021
1 parent b9da4cb commit a1523bf
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
21 changes: 20 additions & 1 deletion lib/mime/application.ex
Original file line number Diff line number Diff line change
Expand Up @@ -96,13 +96,28 @@ defmodule MIME.Application do
iex> MIME.extensions("application/json")
["json"]
iex> MIME.extensions("application/vnd.custom+xml")
["xml"]
iex> MIME.extensions("foo/bar")
[]
"""
@spec extensions(String.t()) :: [String.t()]
def extensions(type) do
mime_to_ext(downcase(type, "")) || []
mime =
type
|> strip_params()
|> downcase("")

mime_to_ext(mime) || suffix(mime) || []
end

defp suffix(type) do
case String.split(type, "+") do
[type_subtype_without_suffix, suffix] -> [suffix]
_ -> nil
end
end

@default_type "application/octet-stream"
Expand Down Expand Up @@ -161,6 +176,10 @@ defmodule MIME.Application do
end
end

defp strip_params(string) do
string |> :binary.split(";") |> hd()
end

defp downcase(<<h, t::binary>>, acc) when h in ?A..?Z,
do: downcase(t, <<acc::binary, h + 32>>)

Expand Down
7 changes: 6 additions & 1 deletion test/mime_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,15 @@ defmodule MIMETest do
end

test "extensions/1" do
assert "json" in extensions("application/json")
assert extensions("application/json") == ["json"]
assert extensions("application/vnd.api+json") == ["json-api"]
assert extensions("audio/amr") == ["amr"]
assert extensions("IMAGE/PNG") == ["png"]

assert extensions("application/json; charset=utf-8") == ["json"]

assert extensions("application/vnd.custom+xml") == ["xml"]
assert extensions("application/vnd.custom+xml+xml") == []
end

test "type/1" do
Expand Down

0 comments on commit a1523bf

Please sign in to comment.