responseDataHandler function
Handle response for different types of data such as string, stream, file, Model, List, encodable.
Implementation
void responseDataHandler(dynamic payload, HttpRequest request) {
HttpResponse res = request.response;
if (payload == null) {
res.close();
return;
}
/// file on disk: streamed, with Content-Length and Range support
if (payload is File) {
_pipe(request, _sendFile(payload, request));
return;
}
/// if payload is stream
if (payload is StreamFile) {
res.headers.contentType = payload.contentType;
if (payload.length != null) res.contentLength = payload.length!;
_pipe(request, res.addStream(payload.stream));
return;
}
/// if payload is downloadable file,
/// we response contentDisposition header with stream data.
if (payload is DownloadableFile) {
res.headers.contentType = payload.contentType;
res.headers.add(FILE_DOWNLOAD_HEADER, payload.contentDisposition);
if (payload.length != null) res.contentLength = payload.length!;
_pipe(request, res.addStream(payload.stream));
return;
}
// if payload is stream, pipe it chunk by chunk (no buffering)
if (payload is Stream<List<int>>) {
_pipe(request, res.addStream(payload));
return;
}
/// if payload handle base Http Exception
/// we set http status from exception and return as map
/// which will parse into json and response as json
if (payload is IHttpException) {
res.statusCode = payload.code;
payload = payload.toResponse();
}
if (payload is Exception || payload is Error) {
res.statusCode = HttpStatus.internalServerError;
payload = payload.toString();
}
if (payload is DateTime) {
payload = payload.toIso8601String();
}
List<int> bytes;
/// if payload is Map or List, parse into json
/// and response as json
if (payload is! String) {
bytes = _jsonUtf8.convert(payload);
res.headers.contentType = ContentType.json;
} else {
bytes = res.encoding.encode(payload);
}
/// finally write and close http connection.
/// known length lets the client skip chunked decoding.
/// dart:io only gzips when the length is not set, so skip it then.
if (!Dox().config.compress) res.contentLength = bytes.length;
res.add(bytes);
res.close();
}