onRequest method

  1. @override
void onRequest(
  1. RequestOptions options,
  2. RequestInterceptorHandler handler
)

Called when the request is about to be sent.

Implementation

@override
void onRequest(
    dio.RequestOptions options, dio.RequestInterceptorHandler handler) {
  // Decided once per attempt and always overwritten, so a mid-flight options
  // change or a retry reusing these options cannot act on a stale decision.
  final globalOptions = CxFlutterPlugin.globalOptions;
  final networkOff = globalOptions != null &&
      !globalOptions.isInstrumentationEnabled(CXInstrumentationType.network);
  options.extra[_kNetworkOffKey] = networkOff;
  _clearInjectedTraceContext(options);
  if (networkOff) {
    handler.next(options);
    return;
  }

  // Monotonic clock: wall time can jump (NTP sync, timezone change) mid-request.
  options.extra[_kStopwatchKey] = Stopwatch()..start();

  if (globalOptions != null &&
      Utils.shouldAddTraceParent(options.uri.toString(), globalOptions)) {
    final spanId = Utils.generateHex(16);

    final traceId = Utils.resolveTraceId();

    final traceParent = _generateTraceParent(traceId, spanId);
    options.headers['traceparent'] = traceParent;
    options.extra[_kInjectedHeaderKey] = traceParent;
    options.extra[_kTraceIdKey] = traceId;
    options.extra[_kSpanIdKey] = spanId;
  }

  handler.next(options);
}