-
Notifications
You must be signed in to change notification settings - Fork 0
/
ip.go
74 lines (56 loc) · 1.7 KB
/
ip.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package api
import (
"net"
"github.com/rs/zerolog/log"
"github.com/valyala/fasthttp"
)
func getIPVersion(ip net.IP) string {
if ip.To4() == nil {
return "6"
}
return "4"
}
// GetIP handle the request and send back the public ip address.
func GetIP(ctx *fasthttp.RequestCtx) Response {
var header *fasthttp.RequestHeader = &ctx.Request.Header
// Standard forward header
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Forwarded
var ip net.IP = net.ParseIP(string(header.Peek(fasthttp.HeaderForwarded)))
if len(ip) != 0 {
log.Info().Msg("IP Found via standard Forwarded header field.")
goto ipFound
}
// De-facto standard header
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For
ip = net.ParseIP(string(header.Peek(fasthttp.HeaderXForwardedFor)))
if len(ip) != 0 {
log.Info().Msg("IP Found via non-standard X-Forwarded-For header field.")
goto ipFound
}
// No proxy
ip = ctx.RemoteIP()
// Valid ip address (different from 0.0.0.0 and ::0)
if !ip.Equal(net.IPv4zero) && !ip.Equal(net.IPv6zero) {
log.Info().Msg("IP Found using remote ip. (no proxy)")
goto ipFound
}
// ---------------------------------------------------
// IP NOT FOUND
// ---------------------------------------------------
log.Error().Msg("IP NOT FOUND")
ctx.SetStatusCode(500)
return response{
"code": "500",
"message": "Server failed to identify your ip address.",
}
// ---------------------------------------------------
// IP FOUND
// ---------------------------------------------------
ipFound:
res := response{
"ip": ip.String(),
"version": getIPVersion(ip),
}
log.Info().Str("ip", res["ip"]).Str("version", res["version"]).Msg("")
return res
}