improve uri parsing for urls without scheme

This commit is contained in:
Fabian Freund
2024-06-21 11:02:50 +02:00
parent 259f33bb92
commit 3f1e0a2086
3 changed files with 26 additions and 16 deletions
+17 -7
View File
@@ -1,12 +1,22 @@
Uri? tryParseUrl(String? input) {
Uri? tryParseUrl(String? input, {bool eagerParsing = false}) {
if (input != null) {
final uri = Uri.tryParse(input);
if (uri != null &&
uri.hasAuthority &&
(uri.isScheme('http') || uri.isScheme('https') || !uri.hasScheme)) {
return uri;
var uri = Uri.tryParse(input);
if (uri != null) {
if (uri.authority.isEmpty && eagerParsing) {
//When there is no scheme, there will be no authority/host and all becomes a path
//so we make sure there are at least 2 segments where the first one looks like a domain
if (uri.pathSegments.length > 1 &&
RegExp(r'.[a-z]{2,}$').hasMatch(uri.pathSegments.first)) {
uri = Uri.tryParse('https://$input');
}
}
if (uri != null &&
uri.authority.isNotEmpty &&
(uri.isScheme('http') || uri.isScheme('https') || !uri.hasScheme)) {
return uri;
}
}
}
return null;
}