github.com/craicoverflow/tyk@v2.9.6-rc3+incompatible/request/real_ip_test.go (about) 1 package request 2 3 import ( 4 "context" 5 "net/http" 6 "testing" 7 ) 8 9 var ipHeaderTests = []struct { 10 remoteAddr string 11 key string 12 value string 13 expected string 14 comment string 15 }{ 16 {remoteAddr: "10.0.1.4:8080", key: "X-Real-IP", value: "10.0.0.1", expected: "10.0.0.1", comment: "X-Real-IP"}, 17 {remoteAddr: "10.0.1.4:8080", key: "X-Forwarded-For", value: "10.0.0.2", expected: "10.0.0.2", comment: "X-Forwarded-For (single)"}, 18 {remoteAddr: "10.0.1.4:8080", key: "X-Forwarded-For", value: "10.0.0.3, 10.0.0.2, 10.0.0.1", expected: "10.0.0.3", comment: "X-Forwarded-For (multiple)"}, 19 {remoteAddr: "10.0.1.4:8080", expected: "10.0.1.4", comment: "RemoteAddr"}, 20 } 21 22 func TestRealIP(t *testing.T) { 23 24 for _, test := range ipHeaderTests { 25 t.Log(test.comment) 26 27 r, _ := http.NewRequest(http.MethodGet, "http://abc.com:8080", nil) 28 r.Header.Set(test.key, test.value) 29 r.RemoteAddr = test.remoteAddr 30 31 ip := RealIP(r) 32 33 if ip != test.expected { 34 t.Errorf("\texpected %s got %s", test.expected, ip) 35 } 36 } 37 38 t.Log("Context") 39 r, _ := http.NewRequest(http.MethodGet, "http://abc.com:8080", nil) 40 41 ctx := context.WithValue(r.Context(), "remote_addr", "10.0.0.5") 42 r = r.WithContext(ctx) 43 44 ip := RealIP(r) 45 if ip != "10.0.0.5" { 46 t.Errorf("\texpected %s got %s", "10.0.0.5", ip) 47 } 48 } 49 50 func BenchmarkRealIP_RemoteAddr(b *testing.B) { 51 b.ReportAllocs() 52 53 r, _ := http.NewRequest(http.MethodGet, "http://abc.com:8080", nil) 54 r.RemoteAddr = "10.0.1.4:8081" 55 56 for n := 0; n < b.N; n++ { 57 ip := RealIP(r) 58 if ip != "10.0.1.4" { 59 b.Errorf("\texpected %s got %s", "10.0.1.4", ip) 60 } 61 } 62 } 63 64 func BenchmarkRealIP_ForwardedFor(b *testing.B) { 65 b.ReportAllocs() 66 67 r, _ := http.NewRequest(http.MethodGet, "http://abc.com:8080", nil) 68 r.Header.Set("X-Forwarded-For", "10.0.0.3, 10.0.0.2, 10.0.0.1") 69 70 for n := 0; n < b.N; n++ { 71 ip := RealIP(r) 72 if ip != "10.0.0.3" { 73 b.Errorf("\texpected %s got %s", "10.0.1.3", ip) 74 } 75 } 76 } 77 78 func BenchmarkRealIP_RealIP(b *testing.B) { 79 b.ReportAllocs() 80 81 r, _ := http.NewRequest(http.MethodGet, "http://abc.com:8080", nil) 82 r.Header.Set("X-Real-IP", "10.0.0.1") 83 84 for n := 0; n < b.N; n++ { 85 ip := RealIP(r) 86 if ip != "10.0.0.1" { 87 b.Errorf("\texpected %s got %s", "10.0.0.1", ip) 88 } 89 } 90 } 91 92 func BenchmarkRealIP_Context(b *testing.B) { 93 b.ReportAllocs() 94 95 r, _ := http.NewRequest(http.MethodGet, "http://abc.com:8080", nil) 96 r.Header.Set("X-Real-IP", "10.0.0.1") 97 ctx := context.WithValue(r.Context(), "remote_addr", "10.0.0.5") 98 r = r.WithContext(ctx) 99 100 for n := 0; n < b.N; n++ { 101 ip := RealIP(r) 102 if ip != "10.0.0.5" { 103 b.Errorf("\texpected %s got %s", "10.0.0.5", ip) 104 } 105 } 106 }