Created
February 5, 2016 02:23
-
-
Save dcomartin/ebf8ef2674ccf0b2df03 to your computer and use it in GitHub Desktop.
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
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