github.com/greenpau/go-authcrunch@v1.1.4/pkg/util/addr/utils_test.go (about)

     1  // Copyright 2022 Paul Greenberg greenpau@outlook.com
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package addr
    16  
    17  import (
    18  	"fmt"
    19  	"net/http"
    20  	"testing"
    21  )
    22  
    23  func TestGetSourceAddress(t *testing.T) {
    24  	testFailed := 0
    25  	tests := []struct {
    26  		addr   string
    27  		hname  string
    28  		hvalue string
    29  		result string
    30  	}{
    31  		{
    32  			addr:   "192.168.99.40:23467",
    33  			result: "192.168.99.40",
    34  		},
    35  		{
    36  			addr:   "192.168.99.40:23467",
    37  			hname:  "x-real-ip",
    38  			hvalue: "10.10.10.10",
    39  			result: "10.10.10.10",
    40  		},
    41  		{
    42  			addr:   "192.168.99.40:23467",
    43  			hname:  "X-real-IP",
    44  			hvalue: "10.10.10.10",
    45  			result: "10.10.10.10",
    46  		},
    47  		{
    48  			addr:   "192.168.99.40:23467",
    49  			hname:  "X-Forwarded-For",
    50  			hvalue: "100.100.2.2, 192.168.0.10",
    51  			result: "100.100.2.2",
    52  		},
    53  		{
    54  			addr:   "192.168.99.40:23467",
    55  			hname:  "X-Forwarded-For",
    56  			hvalue: "192.168.0.10",
    57  			result: "192.168.0.10",
    58  		},
    59  	}
    60  	for i, test := range tests {
    61  		r, err := http.NewRequest("GET", "127.0.0.1", nil)
    62  		if err != nil {
    63  			t.Fatalf("Failed creating HTTP request")
    64  		}
    65  		r.RemoteAddr = test.addr
    66  		testDescr := fmt.Sprintf("Test %d, addr: %s, result: %s", i, test.addr, test.result)
    67  		if test.hname != "" {
    68  			testDescr += fmt.Sprintf(", header: %s, value, %s", test.hname, test.hvalue)
    69  			r.Header.Add(test.hname, test.hvalue)
    70  		}
    71  
    72  		addr := GetSourceAddress(r)
    73  		if addr != test.result {
    74  			t.Logf("FAIL: %s, received: %s", testDescr, addr)
    75  			testFailed++
    76  			continue
    77  		}
    78  		t.Logf("PASS: %s", testDescr)
    79  	}
    80  
    81  	if testFailed > 0 {
    82  		t.Fatalf("Failed %d tests", testFailed)
    83  	}
    84  }