| 1 |
package main |
| 2 |
|
| 3 |
import ( |
| 4 |
"fmt" |
| 5 |
"log" |
| 6 |
"net/http" |
| 7 |
|
| 8 |
"github.com/didip/tollbooth/v6" |
| 9 |
"github.com/realclientip/realclientip-go" |
| 10 |
) |
| 11 |
|
| 12 |
func main() { |
| 13 |
|
| 14 |
strat, err := realclientip.NewRightmostNonPrivateStrategy("X-Forwarded-For") |
| 15 |
if err != nil { |
| 16 |
log.Fatal("realclientip.NewRightmostNonPrivateStrategy returned error (bad input)") |
| 17 |
} |
| 18 |
|
| 19 |
lmt := tollbooth.NewLimiter(1, nil) |
| 20 |
|
| 21 |
|
| 22 |
req, _ := http.NewRequest("GET", "https://example.com", nil) |
| 23 |
req.Header.Add("X-Forwarded-For", "1.1.1.1, 2.2.2.2, 3.3.3.3, 192.168.1.1") |
| 24 |
req.RemoteAddr = "192.168.1.2:8888" |
| 25 |
|
| 26 |
clientIP := strat.ClientIP(req.Header, req.RemoteAddr) |
| 27 |
if clientIP == "" { |
| 28 |
|
| 29 |
log.Fatal("strat.ClientIP found no IP") |
| 30 |
} |
| 31 |
|
| 32 |
|
| 33 |
clientIP, _ = realclientip.SplitHostZone(clientIP) |
| 34 |
|
| 35 |
if httpErr := tollbooth.LimitByKeys(lmt, []string{clientIP}); httpErr != nil { |
| 36 |
fmt.Println("We got limited!?!", httpErr) |
| 37 |
} else { |
| 38 |
fmt.Println("Request allowed") |
| 39 |
} |
| 40 |
|
| 41 |
|
| 42 |
} |