using System.IO;
using System.IO.Compression;
using System.Text;
using EmbedIO.Internal;
namespace EmbedIO
{
partial class HttpContextExtensions
{
///
/// Wraps the response output stream and returns a that can be used directly.
/// Optional buffering is applied, so that the response may be sent as one instead of using chunked transfer.
/// Proactive negotiation is performed to select the best compression method supported by the client.
///
/// The on which this method is called.
/// If set to , sent data is collected
/// in a and sent all at once when the returned
/// is disposed; if set to (the default), chunked transfer will be used.
/// if sending compressed data is preferred over
/// sending non-compressed data; otherwise, .
///
/// A that can be used to write response data.
/// This stream MUST be disposed when finished writing.
///
///
public static Stream OpenResponseStream(this IHttpContext @this, bool buffered = false, bool preferCompression = true)
{
// No need to check whether negotiation is successful;
// the returned callback will throw HttpNotAcceptableException if it was not.
_ = @this.Request.TryNegotiateContentEncoding(preferCompression, out var compressionMethod, out var prepareResponse);
prepareResponse(@this.Response);
var stream = buffered ? new BufferingResponseStream(@this.Response) : @this.Response.OutputStream;
return compressionMethod switch {
CompressionMethod.Gzip => new GZipStream(stream, CompressionMode.Compress),
CompressionMethod.Deflate => new DeflateStream(stream, CompressionMode.Compress),
_ => stream
};
}
///
/// Wraps the response output stream and returns a that can be used directly.
/// Optional buffering is applied, so that the response may be sent as one instead of using chunked transfer.
/// Proactive negotiation is performed to select the best compression method supported by the client.
///
/// The on which this method is called.
///
/// The to use to convert text to data bytes.
/// If (the default), (UTF-8 without a byte order mark) is used.
///
/// If set to , sent data is collected
/// in a and sent all at once when the returned
/// is disposed; if set to (the default), chunked transfer will be used.
/// if sending compressed data is preferred over
/// sending non-compressed data; otherwise, .
///
/// A that can be used to write response data.
/// This writer MUST be disposed when finished writing.
///
///
public static TextWriter OpenResponseText(this IHttpContext @this, Encoding? encoding = null, bool buffered = false, bool preferCompression = true)
{
encoding ??= WebServer.DefaultEncoding;
@this.Response.ContentEncoding = encoding;
return new StreamWriter(OpenResponseStream(@this, buffered, preferCompression), encoding);
}
}
}