-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
90 lines (73 loc) · 1.97 KB
/
main.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package main
import (
"encoding/json"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
// return only IP, for no-ip, ddns services alike
r.GET("/ip", func(c *gin.Context) {
if c.GetHeader("X-Forwarded-For") != "" {
c.String(200, "%s", c.GetHeader("X-Forwarded-For"))
} else {
c.String(200, "%s", c.ClientIP())
}
})
// return header, for debugging behind CDN
r.GET("/header", func(c *gin.Context) {
json, err := json.MarshalIndent(c.Request.Header, "", " ")
if err != nil {
c.JSON(500, gin.H{"result": "failed"})
} else {
c.String(200, "%s", json)
}
})
r.GET("/request", func(c *gin.Context) {
json, err := json.MarshalIndent(getRequestInfo(c), "", " ")
if err != nil {
c.JSON(500, gin.H{"result": "failed"})
} else {
c.String(200, "%s", json)
}
})
r.NoRoute(func(c *gin.Context) {
json, err := json.MarshalIndent(getClientInfo(c), "", " ")
if err != nil {
c.JSON(500, gin.H{"result": "failed"})
} else {
c.String(200, "%s", json)
}
})
r.Run()
}
func getClientInfo(c *gin.Context) map[string]string {
client := make(map[string]string)
// Client IP
if c.GetHeader("X-Forwarded-For") != "" {
client["ip"] = c.GetHeader("X-Forwarded-For")
} else {
client["ip"] = c.ClientIP()
}
// CloudFlare
if c.GetHeader("cf-ipcountry") != "" {
client["country"] = countrycode[c.GetHeader("cf-ipcountry")]
}
// CloudFront
if c.GetHeader("Cloudfront-Viewer-Country-Name") != "" {
client["country"] = c.GetHeader("Cloudfront-Viewer-Country-Name")
}
if c.GetHeader("Cloudfront-Viewer-City") != "" {
client["city"] = c.GetHeader("Cloudfront-Viewer-City")
}
return client
}
func getRequestInfo(c *gin.Context) map[string]string {
client := make(map[string]string)
client["host"] = c.Request.Host
client["uri"] = c.Request.RequestURI
client["method"] = c.Request.Method
if c.GetHeader("Cloudfront-Viewer-Http-Version") != "" {
client["proto"] = c.GetHeader("Cloudfront-Viewer-Http-Version")
}
return client
}