Created
April 13, 2016 12:50
-
-
Save mike-ward/3d8d075da52bc0c469b7367d24162d18 to your computer and use it in GitHub Desktop.
Enable gzip compression for assets in NancyFx
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
using System.Collections.Generic; | |
using System.IO.Compression; | |
using System.Linq; | |
using Nancy; | |
using Nancy.Bootstrapper; | |
namespace SendExplorerPlus.Portal.Utilities | |
{ | |
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