3

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?

Fu-Raz
  • 73
  • 7

2 Answers2

0

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.

Gil
  • 3,279
  • 1
  • 15
  • 25
  • Thanks a lot for your response. Do I have to create a main.c file in the /handlers/ dir for the hostname that I want this for? – Fu-Raz Jun 25 '13 at 14:36
  • Yes. Look at the examples for how to choose in **init()** which notification you wish to receive (here HDL_BEFORE_WRITE). The code above goes into the handler **main()**. – Gil Jun 26 '13 at 15:51
  • Be careful: using "\r\n\r\n" make current browsers complain about invalid encode. As RFC states, headers must be concluded with single "\r\n". I wasted hours because of this :-) (please see my ready-to-use main.c below, if interested) – lucaferrario Jun 05 '20 at 16:26
0

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 :-)

lucaferrario
  • 990
  • 9
  • 9