How do I create a G-Wan global variable properly?

113 views Asked by At

--- config.h

extern char userurl[3];
char userurl[3];

--- index.c

include "config.h"

int main(int argc, char *argv[]) {  
    char *req_g="",*req_p="";

    get_arg("g=", &req_g, argc,argv);
    get_arg("p=", &req_p, argc,argv);

    strcat(userurl,req_g);
    strcat(userurl,req_p);
    ..

    xbuf_xcat(reply,"%s",userurl);
    ..

    return 200;
}

Then I used http://127.0.0.1:8080/?index&g=a&p=b

I reload multiple times and the results duplicate: userurl is not freed...

What's the proper way to declare extern or global variables for gwan?

1

There are 1 answers

4
Gil On

Each G-WAN script is compiled separately. As a result, all your variables are static (local to this module) - you cannot share them without using pointers and atomic operations.

In order to ease the use of global variables, G-WAN provides persistent pointers (US_HANDLER_DATA, US_VHOST_DATA, or US_REQUEST_DATA):

void *pVhost_persistent_ptr = (void*)get_env(argv, US_VHOST_DATA);
if(pVhost_persistent_ptr)
   printf("%.4s\n", pVhost_persistent_ptr);

// get a pointer on a pointer (to CHANGE the pointer value)
void **pVhost_persistent_ptr = (void*)get_env(argv, US_VHOST_DATA);
if(pVhost_persistent_ptr)
   *pVhost_persistent_ptr = strdup("persistent data");

Several examples, like persistence.c or stream3.c illustrate how to proceed with real-life programs.