Question

I'm currently running a G-WAN server that hosts static HTML files. Right now I'm using an iframe to show the contents of these files. I would like to be able to load them cross-domain with JavaScript. Which, by default, is not allowed by the browser.

A simple fix is to add the header: Access-Control-Allow-Origin: * to the HTTP response. The problem is, I would like to avoid making a G-WAN servlet for returning static HTML, just to add the header.

Is it possible to add the header by default?

Was it helpful?

Solution

Is it possible to add [HTTP] headers by default?

Sure, add the following code in a G-WAN connection handler:

  case HDL_BEFORE_WRITE:
  {
     char head[] = "Access-Control-Allow-Origin: *\r\n\r\n";
     http_header(HEAD_ADD, head, sizeof(head) - 1, argv);
     break;
  }

This will be available for all replies, static and dynamic.

If you want to be more selective, just add your filter in the code above.

OTHER TIPS

I had to fight for hours to get to these few lines of code that solve the problem perfectly, so I share them here below. First, you have to create a main.c file into handlers folder (please create/rename the folder if it's not existing or it's disabled) of your G-WAN virtualhost and copy/paste what follows:

// Add simple CORS header (Access-Control-Allow-Origin: *) to all resources

#include "gwan.h"   // G-WAN exported functions

int init(int argc, char *argv[])
{
    u32 *states = (u32*)get_env(argv, US_HANDLER_STATES);
    *states = (1 << HDL_BEFORE_WRITE);
    return 0;
}

void clean(int argc, char *argv[])
{
}

int main(int argc, char *argv[])
{
    char head[] = "Access-Control-Allow-Origin: *\r\n";
    http_header(HEAD_ADD, head, sizeof(head) - 1, argv);  
    return(255);
}

Then, kill g-wan, run it as root to compile the script, re-kill and run it as your web user (please change /var/www path with your g-wan root and www-data-user with the web user you're using...also, use sudo if you're not logged in as root):

/var/www/gwan -k
/var/www/gwan

(now CTRL-C to exit)

/var/www/gwan -k
/var/www/gwan -d:www-data:www-data-user

Now all your resources will have a beautiful Access-Control-Allow-Origin: * header :-)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top