Debian Codegraph @

example_middleware_test.go

raw symbols SCIP
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 // Choose the right strategy for our network configuration
16 strat, err := realclientip.NewRightmostNonPrivateStrategy("X-Forwarded-For")
17 if err != nil {
18 log.Fatal("realclientip.NewRightmostNonPrivateStrategy returned error (bad input)")
19 }
20
21 // Place our middleware before the handler
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 // Output:
42 // your IP: 3.3.3.3
43 }
44
45 type clientIPCtxKey struct{}
46
47 // Adds the "real" client IP to the request context under the clientIPCtxKey{} key.
48 // If the client IP couldn't be obtained, the value will be an empty string.
49 // We could use the RightmostNonPrivateStrategy concrete type, but instead we'll pass
50 // around the Strategy interface, in case we decide to change our strategy in the future.
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 // Write error log. Consider aborting the request depending on use.
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 }