Skip to content

Instantly share code, notes, and snippets.

@thecodejunkie
Created November 27, 2012 22:29
Show Gist options
  • Save thecodejunkie/4157605 to your computer and use it in GitHub Desktop.
Save thecodejunkie/4157605 to your computer and use it in GitHub Desktop.
Basic throttling in Nancy
using System;
using System.Runtime.Caching;
using Bootstrapper;
public class Home : NancyModule
{
public Home()
{
Get["/"] = parameters => {
return "Hi";
};
}
}
public class ThrottlingHooks : IApplicationStartup
{
private readonly IThrottleCache cache;
public ThrottlingHooks(IThrottleCache cache)
{
this.cache = cache;
}
public void Initialize(IPipelines pipelines)
{
pipelines.BeforeRequest.AddItemToStartOfPipeline(ctx => {
if (this.cache.IsRateExceeded(ctx.Request.UserHostAddress))
{
return HttpStatusCode.TooManyRequests;
}
return null;
});
pipelines.AfterRequest.AddItemToStartOfPipeline(ctx => {
this.cache.Register(ctx.Request.UserHostAddress);
});
}
}
public interface IThrottleCache
{
bool IsRateExceeded(string host);
void Register(string host);
}
public class InMemoryThrottleCache : IThrottleCache
{
private readonly MemoryCache cache;
public InMemoryThrottleCache()
{
this.cache = new MemoryCache("ThrottlingCache");
}
public bool IsRateExceeded(string host)
{
if (!this.cache.Contains(host))
{
return false;
}
return ((ThrottleToken) this.cache[host]).Count > 10;
}
public void Register(string host)
{
if (!this.cache.Contains(host))
{
this.cache.Add(host, new ThrottleToken(), DateTimeOffset.Now.AddMinutes(1));
}
var token =
this.cache.Get(host) as ThrottleToken;
token.Count++;
}
private class ThrottleToken
{
public int Count { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment