-
Notifications
You must be signed in to change notification settings - Fork 0
/
buchonip.go
98 lines (79 loc) · 2.41 KB
/
buchonip.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
91
92
93
94
95
96
97
98
package main
import (
"flag"
"fmt"
"log"
"net/http"
"os"
"strings"
)
const HTMLPage = `
<!doctype html>
<html>
<head>
<title>BuchónIP - Conozca su IP</title>
<style id="a">body{display:none !important;}</style>
<script>
if(self===top){var a=document.getElementById("a");a.parentNode.removeChild(a);}
else{top.location=self.location;}
</script>
<script async src="https://www.googletagmanager.com/gtag/js?id=%s"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '%s');
</script>
</head>
<body>
<h1>BuchónIP</h1>
<p>Su IP es <b>%s</b></p>
<p>Disponible en <a href="/txt" target="_blank">txt</a> y <a href="/json" target="_blank">json</a></p>
</body>
</html>
`
func parse_ip(remoteAddr string) string {
semicolonIndex := strings.LastIndex(remoteAddr, ":")
return remoteAddr[:semicolonIndex]
}
func log_request(remote_ip *string, req *http.Request) {
log.Printf("%s - \"%s %s\" _code _size %s",
*remote_ip,
req.Method,
req.URL,
req.Header["User-Agent"])
}
func homeHandler(res http.ResponseWriter, req *http.Request) {
res.Header().Set("Server", "BuchonIP/0.1")
res.Header().Set("Content-Type", "text/html; charset=utf-8")
res.Header().Set("X-Frame-Options", "SAMEORIGIN")
remote_ip := parse_ip(req.RemoteAddr)
gAnalId := os.Getenv("GOOGLE_ANALYTICS_ID")
log_request(&remote_ip, req)
fmt.Fprintf(res, HTMLPage, gAnalId, gAnalId, remote_ip)
}
func jsonHandler(res http.ResponseWriter, req *http.Request) {
res.Header().Set("Server", "BuchonIP/0.1")
res.Header().Set("Content-Type", "application/json")
remote_ip := parse_ip(req.RemoteAddr)
log_request(&remote_ip, req)
fmt.Fprintf(res, "{\"ip\": \"%s\"}", remote_ip)
}
func txtHandler(res http.ResponseWriter, req *http.Request) {
res.Header().Set("Server", "BuchonIP/0.1")
res.Header().Set("Content-Type", "text/plain")
remote_ip := parse_ip(req.RemoteAddr)
log_request(&remote_ip, req)
fmt.Fprintf(res, remote_ip)
}
func main() {
host := flag.String("host", "127.0.0.1", "Host")
port := flag.Int("port", 8080, "Port")
flag.Parse()
address := fmt.Sprintf("%s:%d", *host, *port)
log.Printf("Listening at http://%s\n", address)
http.HandleFunc("/", homeHandler)
http.HandleFunc("/json", jsonHandler)
http.HandleFunc("/txt", txtHandler)
log.Fatal(http.ListenAndServe(address, nil))
}