Last active
July 13, 2020 00:48
-
-
Save puffnfresh/91e162556723ec0885e3d01c52b152bd to your computer and use it in GitHub Desktop.
Binding LaunchDarkly C SDK to Lua
This file contains hidden or 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
#include <stdbool.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <time.h> | |
#include <launchdarkly/api.h> | |
#include <openssl/sha.h> | |
#include <lua.h> | |
#include <lauxlib.h> | |
static struct LDClient *launchdarkly_client = NULL; | |
static inline void launchdarkly_init() | |
{ | |
const char *key = getenv("LAUNCHDARKLY_APIKEY"); | |
if (key == NULL) { | |
return; | |
} | |
LDConfigureGlobalLogger(LD_LOG_ERROR, LDBasicLogger); | |
LDGlobalInit(); | |
unsigned int maxwaitmilliseconds = 2000; | |
struct LDConfig *config = LDConfigNew(key); | |
launchdarkly_client = LDClientInit(config, maxwaitmilliseconds); | |
} | |
bool launchdarkly_enabled(const char* name, const char* key) | |
{ | |
unsigned char hash[SHA_DIGEST_LENGTH]; | |
SHA1(key, strlen(key), hash); | |
struct LDUser *user = LDUserNew(hash); | |
LDUserSetAnonymous(user, true); | |
bool result = LDBoolVariation(launchdarkly_client, user, name, false, NULL); | |
LDUserFree(user); | |
return result; | |
} | |
int launchdarkly_is_enabled(lua_State *L) | |
{ | |
const char *name = luaL_checkstring(L, 1); | |
const char *ip_address = luaL_checkstring(L, 2); | |
bool result = launchdarkly_enabled(name, ip_address); | |
lua_pushboolean(L, result); | |
return 1; | |
} | |
int luaopen_launchdarkly(lua_State *L) | |
{ | |
launchdarkly_init(); | |
lua_newtable(L); | |
lua_pushcfunction(L, launchdarkly_is_enabled); | |
lua_setfield(L, -2, "isEnabled"); | |
return 1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment