feat(flutter): 增加目录加载诊断与前台重试
This commit is contained in:
1 parent
d68734cdab
commit
730a96559b
10 files changed
+268
-16
No files matched your search
@@ -80,9 +80,17 @@ class AppConfig {
|
||||
Future<bool> Function(String baseUrl)? probe,
|
||||
String? fallbackBaseUrl,
|
||||
}) async {
|
||||
final candidateProbe = probe ?? _probeBaseUrl;
|
||||
for (final candidate in _probeCandidates) {
|
||||
if (await candidateProbe(candidate)) {
|
||||
final result = probe == null
|
||||
? await _probeBaseUrl(candidate)
|
||||
: await _runInjectedProbe(candidate, probe);
|
||||
if (kDebugMode) {
|
||||
final status = result.ok
|
||||
? 'ok'
|
||||
: 'fail(${result.reason ?? 'request failed'})';
|
||||
debugPrint('[probe] $candidate -> $status');
|
||||
}
|
||||
if (result.ok) {
|
||||
applyRuntimeBaseUrl(candidate);
|
||||
return;
|
||||
}
|
||||
@@ -90,25 +98,43 @@ class AppConfig {
|
||||
applyRuntimeBaseUrl(fallbackBaseUrl ?? defaultBaseUrl);
|
||||
}
|
||||
|
||||
static Future<bool> _probeBaseUrl(String baseUrl) async {
|
||||
static Future<_ProbeResult> _runInjectedProbe(
|
||||
String baseUrl,
|
||||
Future<bool> Function(String baseUrl) probe,
|
||||
) async {
|
||||
try {
|
||||
return _ProbeResult(ok: await probe(baseUrl));
|
||||
} catch (error) {
|
||||
return _ProbeResult(ok: false, reason: error.toString());
|
||||
}
|
||||
}
|
||||
|
||||
static Future<_ProbeResult> _probeBaseUrl(String baseUrl) async {
|
||||
final client = HttpClient()..connectionTimeout = _probeTimeout;
|
||||
try {
|
||||
return await _requestCategories(
|
||||
client,
|
||||
Uri.parse('$baseUrl/app/categories'),
|
||||
).timeout(_probeTimeout);
|
||||
} catch (_) {
|
||||
return false;
|
||||
} catch (error) {
|
||||
return _ProbeResult(ok: false, reason: error.toString());
|
||||
} finally {
|
||||
client.close(force: true);
|
||||
}
|
||||
}
|
||||
|
||||
static Future<bool> _requestCategories(HttpClient client, Uri uri) async {
|
||||
static Future<_ProbeResult> _requestCategories(
|
||||
HttpClient client,
|
||||
Uri uri,
|
||||
) async {
|
||||
final request = await client.getUrl(uri);
|
||||
final response = await request.close();
|
||||
await response.drain<void>();
|
||||
return response.statusCode == 200;
|
||||
final ok = response.statusCode == 200;
|
||||
return _ProbeResult(
|
||||
ok: ok,
|
||||
reason: ok ? null : 'HTTP ${response.statusCode}',
|
||||
);
|
||||
}
|
||||
|
||||
/// 后端返回的是相对路径(/files/...),这里补上服务地址。
|
||||
@@ -118,3 +144,10 @@ class AppConfig {
|
||||
return '$apiBaseUrl$path';
|
||||
}
|
||||
}
|
||||
|
||||
class _ProbeResult {
|
||||
const _ProbeResult({required this.ok, this.reason});
|
||||
|
||||
final bool ok;
|
||||
final String? reason;
|
||||
}
|
||||
Reference in new issue
Block a user