parseHost static method

({String host, int port}) parseHost(
  1. String input
)

Splits host / host:port / [v6]:port. Throws ArgumentError for URLs, paths, credentials or anything else that is not a plain host.

Implementation

static ({String host, int port}) parseHost(String input) {
  final raw = input.trim();
  if (raw.isEmpty) {
    throw ArgumentError.value(input, 'host', 'Host must not be empty');
  }
  if (raw.contains(RegExp(r'[/@?#\s\\]')) || raw.contains('*')) {
    throw ArgumentError.value(
      input,
      'host',
      'Expected a host name or host:port, not a URL or pattern',
    );
  }
  final Uri uri;
  try {
    uri = Uri.parse('https://$raw');
  } on FormatException catch (e) {
    throw ArgumentError.value(input, 'host', 'Invalid host: ${e.message}');
  }
  if (uri.host.isEmpty) {
    throw ArgumentError.value(input, 'host', 'Invalid host');
  }
  final port = uri.hasPort ? uri.port : 443;
  if (port <= 0 || port > 65535) {
    throw ArgumentError.value(input, 'host', 'Invalid port');
  }
  return (host: uri.host, port: port);
}