Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

mime_from_contenttype(::String)::MIME #8

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 25 additions & 1 deletion src/MIMEs.jl
Original file line number Diff line number Diff line change
Expand Up @@ -146,11 +146,35 @@ contenttype_from_mime(MIME"application/x-bogus"()) == "application/x-bogus"
```

# See also:
[`charset_from_mime`](@ref)
[`charset_from_mime`](@ref), [`mime_from_contenttype`](@ref)
"""
contenttype_from_mime(mime::MIME) = let c = charset_from_mime(mime)
c === nothing ? string(mime) : "$(string(mime)); charset=$(lowercase(c))"
end


"""
```julia
mime_from_contenttype(content_type::String[, default::T=nothing])::Union{MIME,T}
```

Extract a MIME from a Content-Type header value. If the input is empty, `default` is returned.

# Examples:
```julia
mime_from_contenttype("application/json; charset=utf-8") == MIME"application/json"()
mime_from_contenttype("application/x-bogus") == MIME"application/x-bogus"()
mime_from_contenttype("") == nothing
mime_from_contenttype("", MIME"application/octet-stream"()) == MIME"application/octet-stream"()
```

# See also:
[`contenttype_from_mime`](@ref)
"""
function mime_from_contenttype(content_type::String, default=nothing)
result = strip(split(content_type, ';')[1])
isempty(result) ? default : MIME(result)
end


end
6 changes: 6 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,12 @@ sub(s) = SubString(s, 1)
@test contenttype_from_mime(MIME"application/json"()) == "application/json; charset=utf-8"
@test contenttype_from_mime(MIME"application/x-bogus"()) == "application/x-bogus"


@test mime_from_contenttype("application/json; charset=utf-8") == MIME"application/json"()
@test mime_from_contenttype("application/x-bogus") == MIME"application/x-bogus"()
@test mime_from_contenttype("") == nothing
@test mime_from_contenttype("", MIME"application/octet-stream"()) == MIME"application/octet-stream"()

# from https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types
const mdn = Dict(
".bin" => "application/octet-stream",
Expand Down