-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
55 lines (41 loc) · 1009 Bytes
/
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
package main
import (
"encoding/json"
"log"
"net/http"
"os"
"strings"
"time"
)
type Response struct {
IP string `json:"ip"`
Timestamp time.Time `json:"timestamp"`
}
func getIp(req *http.Request) string {
if ip := req.Header.Get("X-Forwarded-For"); ip != "" {
return strings.Split(ip, ",")[0]
} else {
return strings.Split(req.RemoteAddr, ":")[0]
}
}
func main() {
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
res, _ := json.Marshal(Response{
IP: getIp(r),
Timestamp: time.Now().UTC(),
})
w.Header().Add("Content-Type", "application/json")
w.Header().Add("Access-Control-Allow-Origin", "*")
w.Header().Add("Access-Control-Allow-Methods", "GET")
w.Write(res)
})
http.HandleFunc("/plain", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(getIp(r)))
})
log.Println("Listening on port " + port)
log.Fatal(http.ListenAndServe(":"+port, nil))
}