-
Notifications
You must be signed in to change notification settings - Fork 0
/
my-address.go
48 lines (39 loc) · 1006 Bytes
/
my-address.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package main
import (
"fmt"
"io"
"log"
"net/http"
"os"
)
func main() {
addr, ok := os.LookupEnv("MY_IP_ADDR")
if !ok {
addr = ":8080"
}
log.Printf("Starting web server with address %s", addr)
http.HandleFunc("/", getRequestIpHandler)
if err := http.ListenAndServe(":8080", nil); err != nil {
panic(fmt.Sprintf("Failed to start web server: %s", err))
}
}
type httpResponseWriter struct {
http.ResponseWriter
}
func (x *httpResponseWriter ) logClientIp(msg string) {
io.WriteString(x.ResponseWriter, msg)
log.Println(msg)
}
func getRequestIpHandler(w http.ResponseWriter, r *http.Request) {
headers := []string{"x-forwarded-for", "true-client-ip"}
msg := fmt.Sprintf("Looking for headers %v\n", headers)
log := httpResponseWriter{w}
log.logClientIp(msg)
for _, header := range headers {
clientIp := r.Header.Get(header)
msg = fmt.Sprintf("%v: %v\n", header, clientIp)
log.logClientIp(msg)
}
msg = fmt.Sprintf("Remote Addr: %v\n", r.RemoteAddr)
log.logClientIp(msg)
}