github.com/msales/pkg/v3@v3.24.0/httpx/util_test.go (about)

     1  package httpx_test
     2  
     3  import (
     4  	"net/http"
     5  	"testing"
     6  
     7  	"github.com/msales/pkg/v3/httpx"
     8  	"github.com/stretchr/testify/assert"
     9  )
    10  
    11  func TestRealIP(t *testing.T) {
    12  	tests := []struct {
    13  		req *http.Request
    14  		ip  string
    15  	}{
    16  		{
    17  			&http.Request{RemoteAddr: "127.0.0.1"},
    18  			"127.0.0.1",
    19  		},
    20  		{
    21  			&http.Request{RemoteAddr: "127.0.0.1:8888"},
    22  			"127.0.0.1",
    23  		},
    24  		{
    25  			&http.Request{
    26  				RemoteAddr: "127.0.0.1",
    27  				Header:     http.Header{http.CanonicalHeaderKey("X-Real-Ip"): []string{"1.2.3.4"}},
    28  			},
    29  			"1.2.3.4",
    30  		},
    31  		{
    32  			&http.Request{
    33  				RemoteAddr: "127.0.0.1",
    34  				Header:     http.Header{http.CanonicalHeaderKey("X-Forwarded-For"): []string{"1.2.3.4"}},
    35  			},
    36  			"1.2.3.4",
    37  		},
    38  		{
    39  			&http.Request{
    40  				RemoteAddr: "127.0.0.1",
    41  				Header: http.Header{
    42  					http.CanonicalHeaderKey("X-Forwarded-For"): []string{"1.2.3.4"},
    43  					http.CanonicalHeaderKey("X-Real-Ip"):       []string{"5.6.7.8"}},
    44  			},
    45  			"1.2.3.4",
    46  		},
    47  	}
    48  
    49  	for _, tt := range tests {
    50  		got := httpx.RealIP(tt.req)
    51  		assert.Equal(t, tt.ip, got)
    52  	}
    53  }