-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
89 lines (68 loc) · 1.55 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
package main
import (
"encoding/json"
"fmt"
"net"
"net/http"
"os"
"time"
)
var authToken = os.Getenv("AUTH_TOKEN")
var egressAddr = &net.TCPAddr{IP: net.ParseIP(os.Getenv("EGRESS_ADDRESS"))}
type PingResponse struct {
Reachable bool `json:"reachable"`
Ping int64 `json:"ping"`
}
func isAuthorized(req *http.Request) bool {
token, hasToken := req.Header["Authorization"]
if !hasToken {
return false
}
if len(token) != 1 {
return false
}
return token[0] == authToken
}
func checkPing(ip, port string) PingResponse {
dialer := net.Dialer{
Timeout: time.Second * 4,
LocalAddr: egressAddr,
}
currentTime := time.Now()
dial, err := dialer.Dial("tcp4", fmt.Sprintf("%s:%s", ip, port))
if err != nil {
return PingResponse{}
}
defer dial.Close()
return PingResponse{
Reachable: true,
Ping: time.Now().Sub(currentTime).Milliseconds(),
}
}
func handlePing(writer http.ResponseWriter, req *http.Request) {
if !isAuthorized(req) {
writer.WriteHeader(403)
return
}
query := req.URL.Query()
ip, ipExists := query["ip"]
port, portExists := query["port"]
if !ipExists || !portExists || len(ip) != 1 || len(port) != 1 {
writer.WriteHeader(400)
return
}
result := checkPing(ip[0], port[0])
data, err := json.Marshal(result)
if err != nil {
writer.WriteHeader(500)
return
}
writer.Header().Set("Content-Type", "application/json")
fmt.Fprintf(writer, string(data))
}
func main() {
http.HandleFunc("/ping", handlePing)
if err := http.ListenAndServe("0.0.0.0:8040", nil); err != nil {
fmt.Println(err)
}
}