wzp
2021-05-13 7d694a9113118daec5be7ac224dab46a3b20f106
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// Copyright 2012 Mark Cavage, Inc.  All rights reserved.
 
'use strict';
 
///--- Helpers
 
/**
 * Cleans up sloppy URLs on the request object, like /foo////bar/// to /foo/bar.
 *
 * @private
 * @function strip
 * @param    {Object} path - a url path to clean up
 * @returns  {String} cleaned path
 */
function strip(path) {
    var cur;
    var next;
    var str = '';
 
    for (var i = 0; i < path.length; i++) {
        cur = path.charAt(i);
 
        if (i !== path.length - 1) {
            next = path.charAt(i + 1);
        }
 
        if (cur === '/' && (next === '/' || (next === '?' && i > 0))) {
            continue;
        }
 
        str += cur;
    }
 
    return str;
}
 
/**
 * Cleans up sloppy URLs on the request object,
 * like `/foo////bar///` to `/foo/bar`.
 *
 * @public
 * @function sanitizePath
 * @returns  {Function} Handler
 */
function sanitizePath() {
    function _sanitizePath(req, res, next) {
        req.url = strip(req.url);
        next();
    }
 
    return _sanitizePath;
}
 
///--- Exports
 
module.exports = sanitizePath;