函数计算(读取OSS)

时间:2025-01-13 19:28:53
const OSS = require('ali-oss'); const http = require('http'); const url = require('url'); const querystring = require('querystring'); const server = http.createServer(function (req, res){ const urlObj = url.parse(req.url) const { pathname: _path } = urlObj; // (_path); if (_path === '/test') { getData(req, res).then(function(result) { const { success, url, error } = result; if (success) { // send the 302 to http avoid to use the data in our internal server res.writeHead(302, { 'Location': url, }); res.end(); } else { res.end(Buffer.from('Get OSS file occured error!')); } }); } else { res.end('Hello world!'); } }); function getData (req) { return new Promise(function(resolve) { const urlObj = url.parse(req.url); const { query } = urlObj; const queryObj = querystring.parse(query); const { path: filePath } = queryObj; readDataFromPath(filePath).then(function(res) { resolve(res); }); }) } // the path shouble like this: protocal://endpoint/filePath function readDataFromPath(recievePath) { const path = decodeURIComponent(recievePath); return new Promise(function (resolve) { const doubleSlashIndex = path.indexOf('//'); const firstSlashIndex = path.indexOf('/', doubleSlashIndex + 2); const protocol = path.slice(0, doubleSlashIndex - 1); const _bucket_endpoint_path = path.slice(doubleSlashIndex + 2, firstSlashIndex); // bucket endpoint path point index const _bkt_ept_pat_pt_ind = _bucket_endpoint_path.indexOf('.'); const bucket = _bkt_ept_pat_pt_ind === -1 ? _bucket_endpoint_path : _bucket_endpoint_path.slice(_bkt_ept_pat_pt_ind); const _file_path = path.slice(firstSlashIndex); let result = { success: true, }; switch(protocol) { case 'oss': // initial OSS Object const store = new OSS({ region: 'xxxx', accessKeyId: 'xxxx', accessKeySecret: 'xxxxx', bucket, }) const url = store.signatureUrl(_file_path, { expires: 3600, response: { 'content-disposition': 'attachment' } }); result.url = url; break; default: result.data = 'A default result from getData function'; break; } resolve(result); }); } server.on('clientError', (err, socket) => { socket.end('HTTP/1.1 400 Bad Request\r\n\r\n'); }); server.listen(9000);