Skip to content

Commit bc07680

Browse files
committed
uri.parse returns a result
1 parent d0890ff commit bc07680

File tree

2 files changed

+108
-98
lines changed

2 files changed

+108
-98
lines changed

src/gleam/uri.gleam

Lines changed: 20 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,6 @@ pub type Uri {
3333
)
3434
}
3535

36-
// Special thanks to Elixir for this algorithm
37-
//
3836
/// Parses a compliant URI string into the `Uri` Type.
3937
/// If the string is not a valid URI string then an error is returned.
4038
///
@@ -48,7 +46,11 @@ pub type Uri {
4846
/// Ok(Uri(scheme: Some("https"), ...))
4947
/// ```
5048
///
51-
pub fn parse(uri_string: String) -> Uri {
49+
pub fn parse(uri_string: String) -> Result(Uri, Nil) {
50+
do_parse(uri_string)
51+
}
52+
53+
fn do_parse(uri_string: String) -> Result(Uri, Nil) {
5254
// From https://tools.ietf.org/html/rfc3986#appendix-B
5355
let pattern =
5456
// 12 3 4 5 6 7 8
@@ -89,31 +91,34 @@ pub fn parse(uri_string: String) -> Uri {
8991
|> result.map(pair.second)
9092
|> option.from_result
9193
let port = case port {
92-
None ->
93-
case scheme {
94-
Some("ftp") -> Some(21)
95-
Some("sftp") -> Some(22)
96-
Some("tftp") -> Some(69)
97-
Some("http") -> Some(80)
98-
Some("https") -> Some(443)
99-
Some("ldap") -> Some(389)
100-
_ -> None
101-
}
94+
None -> default_port(scheme)
10295
_ -> port
10396
}
10497
let scheme =
10598
scheme
10699
|> noneify_empty_string
107100
|> option.map(string.lowercase)
108-
Uri(
101+
Ok(Uri(
109102
scheme: scheme,
110103
userinfo: userinfo,
111104
host: host,
112105
port: port,
113106
path: path,
114107
query: query,
115108
fragment: fragment,
116-
)
109+
))
110+
}
111+
112+
fn default_port(scheme: Option(String)) -> Option(Int) {
113+
case scheme {
114+
Some("ftp") -> Some(21)
115+
Some("sftp") -> Some(22)
116+
Some("tftp") -> Some(69)
117+
Some("http") -> Some(80)
118+
Some("https") -> Some(443)
119+
Some("ldap") -> Some(389)
120+
_ -> None
121+
}
117122
}
118123

119124
fn regex_submatches(pattern: String, string: String) -> List(Option(String)) {

0 commit comments

Comments
 (0)