| 1 |
package realclientip_test |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"fmt" |
| 6 |
"io/ioutil" |
| 7 |
"log" |
| 8 |
"net/http" |
| 9 |
"net/http/httptest" |
| 10 |
|
| 11 |
"github.com/realclientip/realclientip-go" |
| 12 |
) |
| 13 |
|
| 14 |
func Example_middleware() { |
| 15 |
|
| 16 |
strat, err := realclientip.NewRightmostNonPrivateStrategy("X-Forwarded-For") |
| 17 |
if err != nil { |
| 18 |
log.Fatal("realclientip.NewRightmostNonPrivateStrategy returned error (bad input)") |
| 19 |
} |
| 20 |
|
| 21 |
|
| 22 |
handlerWithMiddleware := clientIPMiddleware(strat, http.HandlerFunc(handler)) |
| 23 |
httpServer := httptest.NewServer(handlerWithMiddleware) |
| 24 |
defer httpServer.Close() |
| 25 |
|
| 26 |
req, _ := http.NewRequest("GET", httpServer.URL, nil) |
| 27 |
req.Header.Add("X-Forwarded-For", "1.1.1.1, 2.2.2.2, 3.3.3.3, 192.168.1.1") |
| 28 |
|
| 29 |
client := &http.Client{} |
| 30 |
resp, err := client.Do(req) |
| 31 |
if err != nil { |
| 32 |
log.Fatal(err) |
| 33 |
} |
| 34 |
|
| 35 |
b, err := ioutil.ReadAll(resp.Body) |
| 36 |
if err != nil { |
| 37 |
log.Fatal(err) |
| 38 |
} |
| 39 |
|
| 40 |
fmt.Printf("%s", b) |
| 41 |
|
| 42 |
|
| 43 |
} |
| 44 |
|
| 45 |
type clientIPCtxKey struct{} |
| 46 |
|
| 47 |
|
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
func clientIPMiddleware(strat realclientip.Strategy, next http.Handler) http.Handler { |
| 52 |
fn := func(w http.ResponseWriter, r *http.Request) { |
| 53 |
clientIP := strat.ClientIP(r.Header, r.RemoteAddr) |
| 54 |
if clientIP == "" { |
| 55 |
|
| 56 |
log.Fatal("Failed to find client IP") |
| 57 |
} |
| 58 |
|
| 59 |
r = r.WithContext(context.WithValue(r.Context(), clientIPCtxKey{}, clientIP)) |
| 60 |
next.ServeHTTP(w, r) |
| 61 |
} |
| 62 |
|
| 63 |
return http.HandlerFunc(fn) |
| 64 |
} |
| 65 |
|
| 66 |
func handler(w http.ResponseWriter, r *http.Request) { |
| 67 |
clientIP := r.Context().Value(clientIPCtxKey{}) |
| 68 |
fmt.Fprintln(w, "your IP:", clientIP) |
| 69 |
} |