export httpx.GetRemoteAddr
This commit is contained in:
14
rest/httpx/util.go
Normal file
14
rest/httpx/util.go
Normal file
@@ -0,0 +1,14 @@
|
||||
package httpx
|
||||
|
||||
import "net/http"
|
||||
|
||||
const xForwardFor = "X-Forward-For"
|
||||
|
||||
// Returns the peer address, supports X-Forward-For
|
||||
func GetRemoteAddr(r *http.Request) string {
|
||||
v := r.Header.Get(xForwardFor)
|
||||
if len(v) > 0 {
|
||||
return v
|
||||
}
|
||||
return r.RemoteAddr
|
||||
}
|
||||
18
rest/httpx/util_test.go
Normal file
18
rest/httpx/util_test.go
Normal file
@@ -0,0 +1,18 @@
|
||||
package httpx
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestGetRemoteAddr(t *testing.T) {
|
||||
host := "8.8.8.8"
|
||||
r, err := http.NewRequest(http.MethodGet, "/", strings.NewReader(""))
|
||||
assert.Nil(t, err)
|
||||
|
||||
r.Header.Set(xForwardFor, host)
|
||||
assert.Equal(t, host, GetRemoteAddr(r))
|
||||
}
|
||||
Reference in New Issue
Block a user