Skip to content

Instantly share code, notes, and snippets.

@scottoffen
Created June 7, 2017 16:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scottoffen/94a3ea6894fdfa66697d09ab4dbba3ec to your computer and use it in GitHub Desktop.
Save scottoffen/94a3ea6894fdfa66697d09ab4dbba3ec to your computer and use it in GitHub Desktop.
Grapevine: Manual Registration of a Singleton

Create the class that manages the list of APIs as a singleton.

public class ApiKeyManager
{
    private static ApiKeyManager _instance;
    public readonly List<string> ApiKeys = new List<string>();

    private ApiKeyManager() {}

    public static ApiKeyManager GetInstance()
    {
        return _instance ?? (_instance = new ApiKeyManager());
    }

    public IHttpContext AddToList(IHttpContext context)
    {
        ApiKeys.Add(context.Request.PathParameters["value"]);
        context.Response.SendResponse(HttpStatusCode.Ok);
        return context;
    }

    public IHttpContext RemoveFromList(IHttpContext context)
    {
        ApiKeys.Remove(context.Request.PathParameters["value"]);
        context.Response.SendResponse(HttpStatusCode.Ok);
        return context;
    }

    public IHttpContext GetFromList(IHttpContext context)
    {
        var idx = int.Parse(context.Request.PathParameters["index"]);
        var val = ApiKeys.Count > idx ? (string)ApiKeys[idx] : null;
        context.Response.SendResponse(HttpStatusCode.Ok, val);
        return context;
    }
}

Manually register the routes.

server.Router.Register(ApiKeyManager.GetInstance().AddToList, HttpMethod.POST, "/list/[value]");
server.Router.Register(ApiKeyManager.GetInstance().RemoveFromList, HttpMethod.DELETE, "/list/[value]");
server.Router.Register(ApiKeyManager.GetInstance().GetFromList, HttpMethod.GET, "/list/[index]");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment