forked from vandadnp/flutter-tips-and-tricks
-
Notifications
You must be signed in to change notification settings - Fork 1
/
check-if-website-is-up-or-down-in-dart.dart
47 lines (42 loc) · 1.22 KB
/
check-if-website-is-up-or-down-in-dart.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// Want to support my work 🤝? https://buymeacoffee.com/vandad
class UpStatus {
final bool isUp;
final DateTime timestamp;
const UpStatus(this.isUp, this.timestamp);
}
class Pling {
final String url;
final Duration interval;
const Pling({
required this.url,
required this.interval,
});
Stream<UpStatus> checkIfUp() =>
Stream.periodic(interval, (_) => DateTime.now()).asyncExpand(
(now) => HttpClient()
.headUrl(Uri.parse(url))
.then((req) => req..followRedirects = false)
.then((req) => req.close())
.then((resp) => resp.statusCode)
.then((statusCode) => statusCode == 200)
.onError((error, stackTrace) => false)
.then((isUp) => UpStatus(isUp, now))
.asStream(),
);
}
const oneSecond = Duration(seconds: 1);
const url = 'https://dart.dev';
extension IsOrIsNot on bool {
String get isOrIsNot => this ? 'is' : 'is not';
}
void testIt() async {
final pling = Pling(
url: url,
interval: oneSecond,
);
await for (final upStatus in pling.checkIfUp()) {
final timestamp = upStatus.timestamp;
final isUpStr = upStatus.isUp.isOrIsNot;
print('$url $isUpStr up at $timestamp');
}
}