forked from blackjokie/example-app
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
91 lines (77 loc) · 1.83 KB
/
main.go
File metadata and controls
91 lines (77 loc) · 1.83 KB
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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"time"
)
var startTime time.Time
type PingResponse struct {
Message string `json:"message"`
Time time.Time `json:"time"`
Uptime string `json:"uptime"`
AppName string `json:"app_name"`
Env string `json:"env"`
}
func main() {
startTime = time.Now()
http.HandleFunc("/ping", handlePing)
http.HandleFunc("/", handleRoot)
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
fmt.Printf("Server started on port %s\n", port)
http.ListenAndServe(":"+port, nil)
}
func handlePing(w http.ResponseWriter, r *http.Request) {
currentTime := time.Now()
uptime := time.Since(startTime).String()
appName := os.Getenv("APP_NAME")
if appName == "" {
appName = "your_ip"
}
env := os.Getenv("ENV")
if env == "" {
env = "playground"
}
response := PingResponse{
Message: "pong",
Time: currentTime,
Uptime: uptime,
AppName: appName,
Env: env,
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(response)
}
func handleRoot(w http.ResponseWriter, r *http.Request) {
// Check if the X-Forwarded-For header is provided (typical with proxies)
clientIP := r.Header.Get("X-Forwarded-For")
if clientIP == "" {
// Directly fetch the public IP without using r.RemoteAddr as a fallback
publicIP, err := getPublicIP()
if err != nil {
clientIP = "unable to determine your IP"
} else {
clientIP = publicIP
}
}
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(http.StatusOK)
w.Write([]byte("Your IP Address : " + clientIP))
}
func getPublicIP() (string, error) {
resp, err := http.Get("https://api.ipify.org?format=text")
if err != nil {
return "", err
}
defer resp.Body.Close()
ip, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(ip), nil
}