File tree Expand file tree Collapse file tree 1 file changed +61
-0
lines changed
websites/code/studygolang/src/util Expand file tree Collapse file tree 1 file changed +61
-0
lines changed Original file line number Diff line number Diff line change 1+ // Copyright 2014 The StudyGolang Authors. All rights reserved.
2+ // Use of this source code is governed by a BSD-style
3+ // license that can be found in the LICENSE file.
4+ // http://studygolang.com
5+ // Author:polaris [email protected] 6+
7+ package util
8+
9+ import (
10+ "encoding/binary"
11+ "net"
12+ "net/http"
13+ "strings"
14+ )
15+
16+ func Ip (req * http.Request ) string {
17+ ips := proxy (req )
18+ if ips != nil && ips [0 ] != "" {
19+ pos := strings .LastIndex (ips [0 ], ":" )
20+ if pos == - 1 {
21+ return ips [0 ]
22+ } else {
23+ return ips [0 ][:pos ]
24+ }
25+ }
26+
27+ remoteAddr := req .Header .Get ("Remote_addr" )
28+ if remoteAddr == "" {
29+ remoteAddr = req .Header .Get ("X-Real-IP" )
30+ if remoteAddr == "" {
31+ remoteAddr = req .RemoteAddr
32+ }
33+ }
34+
35+ if remoteAddr == "" {
36+ return "127.0.0.1"
37+ }
38+
39+ pos := strings .LastIndex (remoteAddr , ":" )
40+ if pos == - 1 {
41+ return remoteAddr
42+ } else {
43+ return remoteAddr [:pos ]
44+ }
45+ }
46+
47+ func proxy (req * http.Request ) []string {
48+ if ips := req .Header .Get ("X-Forwarded-For" ); ips != "" {
49+ return strings .Split (ips , "," )
50+ }
51+ return nil
52+ }
53+
54+ func Ip2long (ipstr string ) uint32 {
55+ ip := net .ParseIP (ipstr )
56+ if ip == nil {
57+ return 0
58+ }
59+ ip = ip .To4 ()
60+ return binary .BigEndian .Uint32 (ip )
61+ }
You can’t perform that action at this time.
0 commit comments