Skip to content
Merged
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
1 change: 1 addition & 0 deletions docs/src/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ true

```@docs
URI
Base.tryparse(::Type{URI}, ::AbstractString)
queryparams
queryparampairs
absuri
Expand Down
18 changes: 18 additions & 0 deletions src/URIs.jl
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,24 @@ parse_uri_reference(str; strict = false) =

Base.parse(::Type{URI}, str::AbstractString) = parse_uri_reference(str)

"""
tryparse(URI, str::AbstractString) -> Union{URI,Nothing}

Parse `str` as a URI reference. Return `nothing` instead of throwing a
`URIs.ParseError` when parsing fails.

Like `parse(URI, str)`, this accepts both absolute URIs and relative URI
references.
"""
function Base.tryparse(::Type{URI}, str::AbstractString)
try
return parse(URI, str)
catch e
e isa ParseError && return nothing
rethrow()
end
end

function ensurevalid(uri::URI)
# https://tools.ietf.org/html/rfc3986#section-3.1
# ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
Expand Down
3 changes: 3 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,6 @@ end
Base.codeunits(x::CustomString) = codeunits(x.str)

@test URIs.escapeuri(CustomString("http://example.com")) == URIs.escapeuri("http://example.com")

# `tryparse` must rethrow errors other than parse failures.
@test_throws MethodError tryparse(URI, CustomString("http://example.com"))
4 changes: 4 additions & 0 deletions test/uri.jl
Original file line number Diff line number Diff line change
Expand Up @@ -500,6 +500,10 @@ urltests = URLTest[
@test parse(URI, "s3://bucket/key") == URI(host="bucket", path="/key", scheme="s3")

@test sprint(show, parse(URI, "http://google.com")) == "URI(\"http://google.com\")"

@test tryparse(URI, "http://google.com") == URI("http://google.com")
@test tryparse(URI, "../relative/path") == URI("../relative/path")
@test tryparse(URI, "http://example.com/\rheader") === nothing
end

@testset "Characters" begin
Expand Down
Loading