HTTP 요청과 응답을 가로채고 수정할 수 있는 Dart 패키지입니다. 로깅, 인증 헤더, 오류 처리와 같은 관점 간 관심사(크로스 커팅 콘서닝)를 HTTP 호출 전반에 걸쳐 추가하는 깔끔한 방법을 제공합니다. `http` 패키지와 함께 사용하도록 설계되어 개발자가 예측 가능한 요청/응답 처리를 위해 인터셉터를 체인으로 연결할 수 있습니다. 디버깅, 보안 및 Flutter 앱에서 일관된 API 상호작용 유지에 이상적입니다.
사용 사례
API 요청 로깅
인증 헤더 삽입
전역 오류 처리
요청/응답 변환
네트워크 호출 디버깅
중앙 집중형 HTTP 로직
주요 기능
체인 가능한 인터셉터
요청/응답 수정
http 패키지와의 간편한 통합
동기 및 비동기 작업을 지원합니다
사용자 정의 로직을 위한 확장 가능
크로스플랫폼 호환성
적합한 대상
중앙 집중식 HTTP 제어가 필요한 개발자
보안 토큰 관리가 필요한 앱
관측성 및 디버깅에 중점을 둔 팀
http 패키지를 광범위하게 사용하는 프로젝트
복잡한 API 상호작용 패턴을 가진 애플리케이션
고려 사항
인터셉터 패턴에 대한 이해가 필요합니다
간단한 HTTP 호출에 대해 복잡성을 증가시킬 수 있습니다
비동기 작업을 신중하게 처리해야 합니다
완전한 HTTP 클라이언트의 대체품이 아님
http 패키지 통합에 제한됨
원본 README
연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.
HttpTools
A comprehensive collection of Dart and Flutter packages for HTTP request handling, providing intercepting, logging, and caching capabilities to enhance your network operations.
✅ Smart Binary Detection - Clean logs without garbage data
✅ Production Ready - Configurable for development vs production
✅ Human Readable - Clean, structured log format
Log Output Examples:
[a1b2c3d4] --> GET https://api.example.com/users/123
[a1b2c3d4] authorization: Bearer ***
[a1b2c3d4] content-type: application/json
[a1b2c3d4] --> END GET
[a1b2c3d4] <-- 200OK (145ms)
[a1b2c3d4] content-type: application/json
[a1b2c3d4] {"id": 123, "name": "John Doe"}
[a1b2c3d4] <-- END
Usage:
import'package:http_client_logger/http_client_logger.dart';
import'package:logging/logging.dart'hideLevel;
// Set up loggingLogger.root.onRecord.listen((record) => print(record.message));
// Configure loggerHttpClientProxy(
interceptors: [
HttpLogger(
level: Level.body, // basic | headers | body
logBodyContentTypes: {'application/json'}, // Only log JSON as text
),
],
)
http_client_cache
HTTP caching with disk/memory storage - Improve performance and reduce network usage
Key Features:
✅ RFC 7234 Compliant - Standard HTTP caching behavior
✅ Memory & Disk Storage - Choose what fits your needs
✅ Cache-Control Support - Respects server cache directives
✅ Stale-While-Revalidate - Serve stale content while updating
✅ Stale-If-Error - Fallback to cache when network fails
✅ Automatic Cleanup - LRU eviction and size limits
✅ Private Content Filtering - Secure handling of sensitive data
Cache Behavior Examples:
Cache miss for https://api.example.com/posts/1 # First requestCache hit for https://api.example.com/posts/1 # Served from cacheCache entry expired for https://api.example.com/posts/1 # Needs refreshServing stale content due to network error # Stale-if-error fallback
HttpClientProxy(
interceptors: [
if (kDebugMode) HttpLogger(level: Level.body), // Only log in debugAuthInterceptor(apiKey),
cache,
],
)
Custom Cache Control
classCacheControlInterceptorextendsHttpInterceptor{
@overrideFutureOr<OnResponse> onResponse(StreamedResponse response) {
final headers = Map<String, String>.from(response.headers);
// Cache API responses with resilience featuresif (response.request?.url.path.startsWith('/api/') ?? false) {
headers['cache-control'] =
'max-age=300, stale-while-revalidate=60, stale-if-error=3600';
// Cache for 5 min, serve stale for 1 min while revalidating,// serve stale for 1 hour if network fails
}
returnOnResponse.next(response.copyWith(headers: headers));
}
}
🔗 Framework Compatibility
Works seamlessly with popular HTTP packages:
✅ http - A composable, multi-platform, Future-based API for HTTP requests.
✅ chopper - An http client generator using source_gen, inspired by Retrofit
✅ retrofit - An dio client generator using source_gen and inspired by Chopper and Retrofit
Note:dio and retrofit (which uses dio) require the dio_compatibility_layer package to work with the standard http package that these interceptors depend on.
dependencies:http:^1.2.0dio_compatibility_layer:^3.0.0# Required for dio/retrofit compatibility
📊 Performance Considerations
Development vs Production:
HttpClientProxy(
interceptors: [
// Production: Only basic loggingif (kReleaseMode) HttpLogger(level: Level.basic),
// Development: Full logging with bodies if (kDebugMode) HttpLogger(level: Level.body),
// Always cache for better performance
cache,
],
)
Memory Management:
Cache automatically manages size with LRU eviction
Use cache.clearCache() when memory is low
Use cache.deletePrivateContent() when user logs out