UNPKG

2.29 kBJavaScriptView Raw
1var debug = require('debug')('clam:jsonHandle');
2var config = require('./config.js');
3var _ = require('underscore');
4var http = require('http');
5var joinbuffers = require('joinbuffers');
6var path = require('path');
7
8function jsonHandle() {
9 return function (req, res, next) {
10 var prjInfo = config.get('project');
11 var url = req.url;
12 if(url.indexOf('?') != -1){
13 url = url.slice(0, url.indexOf('?'));
14 }
15 var isJson = false;
16 var jsonHandles = prjInfo.json;
17 if(!jsonHandles || jsonHandles.length === 0){
18 next();
19 return;
20 }
21 for(var i = 0; i < jsonHandles.length; i++){
22 var map = jsonHandles[i];
23 var re = new RegExp(map.url);
24 if (url.match(re)) {
25 isJson = true;
26 if(map.enabled === 'local'){
27 //到本地找
28 var localFile = path.join(config.root(), '.clam/json', map.local);
29 var localHandle = require(localFile);
30 if(localHandle(req, res)){
31 return;
32 }
33 }
34
35 http.get({host:map.remote, port:80, path:req.url},function (resp) {
36 var buffs = [];
37 if (resp.statusCode !== 200) {
38 res.end('File ' + url + ' not found.');
39 return;
40 }
41 resp.on('data', function (chunk) {
42 buffs.push(chunk);
43 });
44 resp.on('end', function () {
45 var buff = joinbuffers(buffs);
46
47 //fix 80% situation bom problem.quick and dirty
48 if (buff[0] === 239 && buff[1] === 187 && buff[2] === 191) {
49 buff = buff.slice(3, buff.length);
50 }
51 res.setHeader("Content-Type", "text/html");
52 res.end(buff);
53 });
54 }).on('error', function (e) {
55 debug(e);
56 });
57 break;
58 }
59 }
60 if(!isJson){
61 next();
62 }
63 }
64}
65exports.json = jsonHandle;
\No newline at end of file