Lidarr/NzbDrone.Api/Extensions/GZipPipeline.cs

45 lines
1.3 KiB
C#
Raw Normal View History

2013-06-11 00:17:57 +00:00
using System.IO;
using System.IO.Compression;
using System.Linq;
using Nancy;
namespace NzbDrone.Api.Extensions
{
public static class GzipCompressionPipeline
{
public static void Handle(NancyContext context)
{
2013-07-07 03:56:33 +00:00
context.Response.CompressResponse(context.Request);
}
public static Response CompressResponse(this Response response, Request request)
{
if (!response.ContentType.Contains("image") && request.Headers.AcceptEncoding.Any(x => x.Contains("gzip")))
2013-06-11 00:17:57 +00:00
{
var data = new MemoryStream();
2013-07-07 03:56:33 +00:00
response.Contents.Invoke(data);
2013-06-11 00:17:57 +00:00
data.Position = 0;
if (data.Length < 1024)
{
2013-07-07 03:56:33 +00:00
response.Contents = stream =>
2013-06-11 00:17:57 +00:00
{
data.CopyTo(stream);
stream.Flush();
};
}
else
{
2013-07-07 03:56:33 +00:00
response.Headers["Content-Encoding"] = "gzip";
response.Contents = s =>
2013-06-11 00:17:57 +00:00
{
var gzip = new GZipStream(s, CompressionMode.Compress, true);
data.CopyTo(gzip);
gzip.Close();
};
}
}
2013-07-07 03:56:33 +00:00
return response;
2013-06-11 00:17:57 +00:00
}
}
}