doWrite method

void doWrite(
  1. dynamic data,
  2. dynamic options, [
  3. dynamic callback
])

Performs the write.

Implementation

void doWrite(data, options, [callback]) {
  var self = this;

  // explicit UTF-8 is required for pages not served under utf
  var isString = data is String;
  var contentType =
      isString ? 'text/plain; charset=UTF-8' : 'application/octet-stream';

  final headers = <String, dynamic>{'Content-Type': contentType};

  respond(data) {
    headers[HttpHeaders.contentLengthHeader] =
        data is String ? utf8.encode(data).length : data.length;
    var res = self.connect!.request.response;

    // If the status code is 101 (aka upgrade), then
    // we assume the WebSocket transport has already
    // sent the response and closed the socket
    if (res.statusCode != 101) {
      res.statusCode = 200;

      res.headers.clear(); // remove all default headers.
      this.headers(connect!, headers).forEach((k, v) {
        res.headers.set(k, v);
      });
      try {
        if (data is String) {
          res.write(data);
          connect!.close();
        } else {
          if (headers.containsKey(HttpHeaders.contentEncodingHeader)) {
            res.add(data);
          } else {
            res.write(String.fromCharCodes(data));
          }
          connect!.close();
        }
      } catch (e) {
        var fn = _reqCloses.remove(connect);
        if (fn != null) fn();
        rethrow;
      }
    }
    callback();
  }

  if (httpCompression == null || options['compress'] != true) {
    respond(data);
    return;
  }

  var len = isString ? utf8.encode(data).length : data.length;
  if (len < httpCompression?['threshold']) {
    respond(data);
    return;
  }

  var encodings =
      connect!.request.headers.value(HttpHeaders.acceptEncodingHeader);
  var hasGzip = encodings!.contains('gzip');
  if (!hasGzip && !encodings.contains('deflate')) {
    respond(data);
    return;
  }
  var encoding = hasGzip ? 'gzip' : 'deflate';
//    this.compress(data, encoding, (err, data) {
//      if (err != null) {
//        self.req.response..statusCode = 500..close();
//        callback(err);
//        return;
//      }

  headers[HttpHeaders.contentEncodingHeader] = encoding;
  respond(hasGzip
      ? gzip.encode(utf8.encode(
          data is List ? String.fromCharCodes(data as List<int>) : data))
      : data);
//    });
}