Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- http = require('http');
- https = require('https');
- // url = require('url');
- qs = require('querystring');
- fs = require('fs');
- serverCfg = require('./server.cfg');
- appCfg = require('./app.cfg');
- mime = require('./lib/mime');
- mimeMap = mime.loads('./mime.types');
- routeMap = {
- 'POST': [
- {
- rule: '/test',
- fn: function(req, res) {
- res.end(JSON.stringify(req.body));
- }
- }
- ]
- };
- function sendFile(path, req, res) {
- if (!/^(HEAD|GET)$/.test(req.method)) {
- res.statusCode = 405;
- return res.end('Method not allowed');
- }
- try {
- var stats = fs.statSync(path);
- }
- catch (err) {
- if (err.code == 'ENOENT') {
- res.statusCode = 404;
- return res.end('Resource not found');
- }
- res.statusCode = 500;
- return res.end('Internal server error');
- }
- if (stats.isFile() || (stats.isDirectory() && fs.existsSync(path += '/index.htm'))) {
- res.setHeader('Content-Type', mimeMap.getContentType(path) || 'application/octet-stream');
- // Sending a 'Content-length' header will disable the default chunked encoding.
- // res.setHeader('Content-Length', stats.size);
- res.setHeader('Last-Modified', stats.mtime);
- if (req.method == 'HEAD') {
- return;
- }
- var stream = fs.createReadStream(path);
- stream.on('error', function(err) {
- console.log(err);
- });
- stream.on('open', function() {
- this.pipe(res);
- });
- }
- else {
- res.statusCode = 403;
- res.end('Forbidden error');
- }
- }
- function processRoutes(req, res) {
- var parts = req.url.split('?');
- var path = parts[0];
- var query = parts[1];
- // убираем повторяющиеся слэши
- path = path.replace(/\/{2,}/g, '/');
- // декодируем путь
- var decodedPath = decodeURI(path);
- // виртуальные пути
- if (req.method in routeMap) {
- var routes = routeMap[req.method];
- var i = routes.length;
- while (i--) {
- var route = routes[i];
- if (route.rule instanceof RegExp) {
- var matches = decodedPath.match(route.rule);
- if (matches) {
- return route.fn.apply(null, [req, res].concat(matches.slice(1)));
- }
- }
- else if (route.rule == decodedPath) {
- return route.fn.call(null, req, res);
- }
- }
- }
- // отдаем статику
- sendFile(serverCfg.webRoot + decodedPath, req, res);
- }
- function requestHandler(req, res) {
- var data = [], length = 0;
- req.on('error', function(err) {
- console.log(err);
- });
- req.on('data', function(chunk) {
- if ((length += chunk.length) > serverCfg.maxRequestLength) {
- res.statusCode = 413;
- res.end('Maximum request length exceeded');
- this.pause();
- }
- data.push(chunk);
- });
- req.on('end', function() {
- console.log('Ends');
- data = Buffer.concat(data);
- var _ = this;
- if (_.method == 'POST' && 'content-type' in _.headers) {
- var contentType = _.headers['content-type'];
- if (contentType == 'application/x-www-form-urlencoded') {
- data = qs.parse(data.toString());
- }
- else if (contentType == 'multipart/form-data') {
- //
- }
- }
- _.body = data;
- processRoutes(_, res);
- });
- }
- server = http.createServer(requestHandler);
- server.listen(serverCfg.port, serverCfg.host);
- console.log('Server running at http://' + serverCfg.host + ':' + serverCfg.port + '/');
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement