Created
August 15, 2011 19:36
-
-
Save chrisnicola/1147568 to your computer and use it in GitHub Desktop.
Gzip Compression Filter for Nancy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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")" ?