1
1
package antch
2
2
3
3
import (
4
+ "encoding/base64"
4
5
"fmt"
5
6
"io"
6
7
"io/ioutil"
@@ -9,6 +10,7 @@ import (
9
10
"net/http/httptest"
10
11
"net/http/httputil"
11
12
"net/url"
13
+ "strings"
12
14
"sync"
13
15
"testing"
14
16
)
@@ -25,22 +27,55 @@ func testProxyHandler(t *testing.T, proxyURL *url.URL) {
25
27
},
26
28
}
27
29
28
- handler := proxyHandler (http .ProxyURL (proxyURL ), backMessageHandler (client ))
30
+ handler := ProxyMiddleware (http .ProxyURL (proxyURL ))( backMessageHandler (client ))
29
31
req , _ := http .NewRequest ("GET" , ts .URL , nil )
30
32
resp , err := handler .Send (req )
31
33
if err != nil {
32
34
t .Fatal (err )
33
35
}
34
36
defer resp .Body .Close ()
35
-
36
37
b , err := ioutil .ReadAll (resp .Body )
37
38
if err != nil {
38
39
t .Fatalf ("ReadAll: %v" , err )
39
40
}
40
41
if g , e := string (b ), "hello world" ; g != e {
41
- t .Error ("expected %s; got %s" , e , g )
42
+ t .Errorf ("expected %s; got %s" , e , g )
42
43
}
43
44
}
45
+
46
+ func TestHTTPAuthProxyHandler (t * testing.T ) {
47
+ // HTTP proxy server with authentication.
48
+ var (
49
+ username = "test"
50
+ password = "test"
51
+ )
52
+ proxyServer := httptest .NewServer (http .HandlerFunc (func (w http.ResponseWriter , r * http.Request ) {
53
+ if r .Method == "CONNECT" {
54
+ auth := strings .SplitN (r .Header .Get ("Proxy-Authorization" ), " " , 2 )
55
+ if len (auth ) != 2 && auth [0 ] != "Basic" {
56
+ w .WriteHeader (401 )
57
+ return
58
+ }
59
+ payload , _ := base64 .StdEncoding .DecodeString (auth [1 ])
60
+ if pair := strings .Split (string (payload ), ":" ); len (pair ) != 2 || ! (pair [0 ] == username && pair [1 ] == password ) {
61
+ w .WriteHeader (401 )
62
+ return
63
+ }
64
+ }
65
+ director := func (req * http.Request ) {
66
+ req .URL .Host = r .Host
67
+ req .URL .Scheme = "http"
68
+ }
69
+ proxy := & httputil.ReverseProxy {Director : director }
70
+ proxy .ServeHTTP (w , r )
71
+ }))
72
+ defer proxyServer .Close ()
73
+
74
+ proxyURL , _ := url .Parse (proxyServer .URL )
75
+ proxyURL .User = url .UserPassword (username , password )
76
+ testProxyHandler (t , proxyURL )
77
+ }
78
+
44
79
func TestHTTPProxyHandler (t * testing.T ) {
45
80
// HTTP proxy server.
46
81
proxyServer := httptest .NewServer (http .HandlerFunc (func (w http.ResponseWriter , r * http.Request ) {
0 commit comments