Skip to content

Instantly share code, notes, and snippets.

@chrisnicola
Created August 15, 2011 19:36
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save chrisnicola/1147568 to your computer and use it in GitHub Desktop.
Save chrisnicola/1147568 to your computer and use it in GitHub Desktop.
Gzip Compression Filter for Nancy
/* A JSON gzip compression filter, which could easily be adapted to any pattern needed. This uses a custom AfterFilter
* type which is just a fancy wrapper of Action<NancyContext>. It's useful for convention based loading of filters
*/
public class GzipCompressionFilter : AfterFilter
{
protected override void Handle(NancyContext ctx)
{
if ((ctx.Response.ContentType == "application/json") && ctx.Request.Headers.AcceptEncoding.Any(
x => x.Contains("gzip")))
{
var jsonData = new MemoryStream();
ctx.Response.Contents.Invoke(jsonData);
jsonData.Position = 0;
if (jsonData.Length < 4096)
{
ctx.Response.Contents = s =>
{
jsonData.CopyTo(s);
s.Flush();
};
}
else
{
ctx.Response.Headers["Content-Encoding"] = "gzip";
ctx.Response.Contents = s =>
{
var gzip = new GZipStream(s, CompressionMode.Compress, true);
jsonData.CopyTo(gzip);
gzip.Close();
};
}
}
}
}
public abstract class AfterFilter
{
public static implicit operator Action<NancyContext>(AfterFilter filter)
{
return filter.Handle;
}
protected abstract void Handle(NancyContext ctx);
}
@tburnett80
Copy link

This was a great example, the only problem is when you receive the header:
"Accept: application/json; charset=utf-8"

the check for equality fails, so why not switch it to say:
"ctx.Response.ContentType.Contains("application/json")" ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment