1 var url
= require('url'),
3 node_static
= require('node-static'),
8 var HttpHandler = function (config
) {
9 var public_html
= config
.public_html
|| 'client/';
10 this.file_server
= new node_static
.Server(public_html
);
13 module
.exports
.HttpHandler
= HttpHandler
;
17 HttpHandler
.prototype.serve = function (request
, response
) {
18 // The incoming requests base path (ie. /kiwiclient)
19 var base_path
= global
.config
.http_base_path
|| '/kiwi',
22 // Trim of any trailing slashes
23 if (base_path
.substr(base_path
.length
- 1) === '/') {
24 base_path
= base_path
.substr(0, base_path
.length
- 1);
27 // Build the regex to match the base_path
28 base_path_regex
= base_path
.replace(/[-/\\^$*+?.()|[\]{}]/g
, '\\$&');
30 // Any asset request to head into the asset dir
31 request
.url
= request
.url
.replace(base_path
+ '/assets/', '/assets/');
33 // Any requests for /client to load the index file
34 if (request
.url
.match(new RegExp('^' + base_path_regex
+ '([/$]|$)', 'i'))) {
38 // If the 'magic' translation is requested, figure out the best language to use from
39 // the Accept-Language HTTP header. If nothing is suitible, serve an empty response,
40 // Kiwi will just use the default en-gb strings baked in to it.
41 if (request
.url
=== '/assets/locales/magic.json') {
42 return serveMagicLocale
.call(this, request
, response
);
45 this.file_server
.serve(request
, response
, function (err
) {
47 response
.writeHead(err
.status
, err
.headers
);
53 var serveMagicLocale = function (request
, response
) {
57 if (request
.headers
['accept-language']) {
58 // Example: en-gb,en;q=0.5
59 langs
= request
.headers
['accept-language'].split(',');
60 available
= (function () {
63 files
= fs
.readdirSync('client/assets/locales');
64 files
.forEach(function (file
) {
65 if (file
.slice(-5) === '.json') {
66 l
.push(file
.slice(0, -5));
71 for (i
= 0; i
< langs
.length
; i
++) {
72 langs
[i
] = langs
[i
].split(';q=');
73 langs
[i
][1] = (typeof langs
[i
][1] === 'string') ? parseFloat(langs
[i
][1]) : 1.0;
75 langs
.sort(function (a
, b
) {
79 for (i
= 0; i
< langs
.length
; i
++) {
80 if (langs
[i
][0] === '*') {
82 } else if (_
.contains(available
, langs
[i
][0])) {
83 return this.file_server
.serveFile('/assets/locales/' + langs
[i
][0] + '.json', 200, {Vary
: 'Accept-Language', 'Content-Language': langs
[i
][0]}, request
, response
);
88 response
.writeHead(200, {
89 'Vary': 'Accept-Language',
90 'Content-Type': 'application/json',
91 'Content-Language': 'en-gb'
93 response
.end('{"en-gb": {"":{}}}');