Skip to content

Instantly share code, notes, and snippets.

@dcomartin
Created February 5, 2016 02:23
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dcomartin/ebf8ef2674ccf0b2df03 to your computer and use it in GitHub Desktop.
Save dcomartin/ebf8ef2674ccf0b2df03 to your computer and use it in GitHub Desktop.
public class NancyGzipCompression : IApplicationStartup
{
public void Initialize(IPipelines pipelines)
{
pipelines.AfterRequest += CheckForCompression;
}
private static void CheckForCompression(NancyContext context)
{
if (!RequestIsGzipCompatible(context.Request))
{
return;
}
if (context.Response.StatusCode != HttpStatusCode.OK)
{
return;
}
if (!ResponseIsCompatibleMimeType(context.Response))
{
return;
}
if (ContentLengthIsTooSmall(context.Response))
{
return;
}
CompressResponse(context.Response);
}
private static void CompressResponse(Response response)
{
response.Headers["Content-Encoding"] = "gzip";
var contents = response.Contents;
response.Contents = responseStream =>
{
using (var compression = new GZipStream(responseStream, CompressionMode.Compress))
{
contents(compression);
}
};
}
private static bool ContentLengthIsTooSmall(Response response)
{
string contentLength;
if (response.Headers.TryGetValue("Content-Length", out contentLength))
{
var length = long.Parse(contentLength);
if (length < 4096)
{
return true;
}
}
return false;
}
private static readonly List<string> ValidMimes = new List<string>
{
"application/json",
"application/json; charset=utf-8"
};
private static bool ResponseIsCompatibleMimeType(Response response)
{
return ValidMimes.Any(x => x == response.ContentType);
}
private static bool RequestIsGzipCompatible(Request request)
{
return request.Headers.AcceptEncoding.Any(x => x.Contains("gzip"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment