Spritetm / libesphttpd

NOTE: THIS CODE IS UNMAINTAINED. Please take a look at https://github.com/chmorgan/libesphttpd instead.
125 stars 109 forks source link

Added userData to allow user to store context variable. #34

Open valkuc opened 7 years ago

valkuc commented 7 years ago

cgiData cannot be used for this purpose in templates (because it's used internally), new userData can - it's dedicated for this.

valkuc commented 7 years ago

Example usage:

void ICACHE_FLASH_ATTR cgi_device_manage_tpl(HttpdConnData *connData, char *token, void **arg)
{
    char buf[128];

    manage_state_t *state = connData->userData;

    if (token == NULL)
    {
        // called at the end of template processing
        if (state != NULL) os_free(state);
        return;
    }

    if (state == NULL)
    {
        state = os_malloc(sizeof(manage_state_t));
        if (state == NULL)
        {
            LOGN(LOG_ERR, "Can't allocate state struct.");
            return;
        }
        os_memset(state, 0, sizeof(manage_state_t));

        int len = httpdFindArg(connData->getArgs, "id", buf, sizeof(buf));
        if (len > 0)
        {
            state->id = atoi(buf);
            //Read state->dev from some storage
        }
        else
        {
            state->dev.active = true;

            //Fill other state->dev fields here
        }

        connData->userData = state;
    }

    if (os_strcmp(token, "foo") == 0)
    {
        os_strcpy(buf, "bar");
    }
    else if (os_strcmp(token, "bar") == 0)
    {
        os_strcpy(buf, "foo");
    }
    //
    // more if else blocks
    //
    else
    {
        os_strcpy(buf, "");
    }

    httpdSend(connData, buf, -1);
}