Skip to content

Commit 81886d1

Browse files
committed
添加remote ip
1 parent 4d523d1 commit 81886d1

File tree

3 files changed

+74
-1
lines changed

3 files changed

+74
-1
lines changed

http/request/pagging_test.go

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,5 +38,4 @@ func TestOffSet(t *testing.T) {
3838
pr = request.NewPageRequestFromHTTP(req)
3939
shoud.Equal(int64(18), pr.Offset())
4040
shoud.Equal(uint(20), pr.PageSize)
41-
4241
}

http/request/remoteip.go

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package request
2+
3+
import (
4+
"net/http"
5+
"strings"
6+
)
7+
8+
var (
9+
// DefaultScanForwareHeaderKey 协商forward ip 的 hander key名称
10+
DefaultScanForwareHeaderKey = []string{"X-Forwarded-For", "X-Real-IP"}
11+
)
12+
13+
// GetRemoteIP todo
14+
func GetRemoteIP(r *http.Request) string {
15+
// 优先获取代理IP
16+
var ip string
17+
for _, key := range DefaultScanForwareHeaderKey {
18+
value := r.Header.Get(key)
19+
20+
if strings.Contains(value, ", ") {
21+
i := strings.Index(value, ", ")
22+
if i == -1 {
23+
i = len(value)
24+
}
25+
26+
ip = value[:i]
27+
break
28+
}
29+
30+
if value != "" {
31+
ip = value
32+
break
33+
}
34+
}
35+
36+
if ip != "" {
37+
return ip
38+
}
39+
40+
// 如果没有获得代理IP则采用RemoteIP
41+
addr := strings.Split(r.RemoteAddr, ":")
42+
if len(addr) == 1 {
43+
return addr[0]
44+
}
45+
46+
return strings.Join(addr[0:len(addr)-1], ":")
47+
}

http/request/remoteip_test.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package request_test
2+
3+
import (
4+
"net/http"
5+
"testing"
6+
7+
"github.com/infraboard/mcube/http/request"
8+
"github.com/stretchr/testify/assert"
9+
)
10+
11+
func TestGetRemoteIpFromHeader(t *testing.T) {
12+
shoud := assert.New(t)
13+
14+
req, _ := http.NewRequest("GET", "/", nil)
15+
req.Header.Set("X-Forwarded-For", "10.10.10.10")
16+
ip := request.GetRemoteIP(req)
17+
shoud.Equal("10.10.10.10", ip)
18+
}
19+
20+
func TestGetRemoteIpFromConn(t *testing.T) {
21+
shoud := assert.New(t)
22+
23+
req, _ := http.NewRequest("GET", "/", nil)
24+
req.RemoteAddr = "10.10.10.10"
25+
ip := request.GetRemoteIP(req)
26+
shoud.Equal("10.10.10.10", ip)
27+
}

0 commit comments

Comments
 (0)