@@ -17,10 +17,71 @@ for (var protocol in protocols) {
1717 h . prototype = protocols [ protocol ] ;
1818 h = new h ( ) ;
1919
20+ h . request = function ( h ) {
21+ return function ( options , callback , redirectOptions ) {
2022
23+ redirectOptions = redirectOptions || { } ;
2124
25+ var max = ( typeof options === 'object' && 'maxRedirects' in options ) ? options . maxRedirects : exports . maxRedirects ;
2226
27+ var redirect = util . extend ( {
28+ count : 0 ,
29+ max : max ,
30+ clientRequest : null ,
31+ userCallback : callback
32+ } , redirectOptions ) ;
2333
34+ if ( redirect . count > redirect . max ) {
35+ var err = new Error ( 'Max redirects exceeded. To allow more redirects, pass options.maxRedirects property.' ) ;
36+ redirect . clientRequest . emit ( 'error' , err ) ;
37+ return redirect . clientRequest ;
38+ }
2439
40+ redirect . count ++ ;
2541
42+ var reqUrl ;
43+ if ( typeof options === 'string' ) {
44+ reqUrl = options ;
45+ } else {
46+ reqUrl = url . format ( util . extend ( {
47+ protocol : protocol
48+ } , options ) ) ;
49+ }
50+
51+ var clientRequest = Object . getPrototypeOf ( h ) . request ( options , redirectCallback ( reqUrl , redirect ) ) ;
52+
53+ if ( ! redirect . clientRequest ) redirect . clientRequest = clientRequest ;
54+
55+ function redirectCallback ( reqUrl , redirect ) {
56+ return function ( res ) {
57+ if ( res . statusCode < 300 || res . statusCode > 399 ) {
58+ return redirect . userCallback ( res ) ;
59+ }
60+
61+ if ( ! ( 'location' in res . headers ) ) {
62+ return redirect . userCallback ( res ) ;
63+ }
64+
65+ var redirectUrl = url . resolve ( reqUrl , res . headers . location ) ;
66+
67+ var proto = url . parse ( redirectUrl ) . protocol ;
68+ proto = proto . substr ( 0 , proto . length - 1 ) ;
69+ return module . exports [ proto ] . get ( redirectUrl , redirectCallback ( reqUrl , redirect ) , redirect ) ;
70+ } ;
71+ }
72+
73+ return clientRequest ;
74+ } ;
75+ } ( h ) ;
76+
77+ // see https://github.com/joyent/node/blob/master/lib/http.js#L1623
78+ h . get = function ( h ) {
79+ return function ( options , cb , redirectOptions ) {
80+ var req = h . request ( options , cb , redirectOptions ) ;
81+ req . end ( ) ;
82+ return req ;
83+ } ;
84+ } ( h ) ;
85+
86+ module . exports [ protocol ] = h ;
2687}
0 commit comments