-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
81 lines (62 loc) · 2.25 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
package main
import (
"fmt"
"io/ioutil"
"net/http"
"os/exec"
"regexp"
)
func getIP(w http.ResponseWriter, r *http.Request) {
ip := r.Header.Get("X-Real-IP")
if ip == "" {
ip = r.RemoteAddr
}
err := addToWhiteList(ip)
if err != nil {
fmt.Println("Error:", err)
// Handle the error response as needed.
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
}
func addToWhiteList(newIPAddress string) error {
serviceFilePath := "/etc/systemd/system/caddy.service"
content, err := ioutil.ReadFile(serviceFilePath)
if err != nil {
fmt.Println("Error reading file:", err)
return err
}
originalString := string(content)
re := regexp.MustCompile(`(WHITE_LIST=)([^"\s]+)`)
match := re.FindString(originalString)
if match != "" {
existingWhiteList := re.FindStringSubmatch(originalString)[2]
newWhiteList := existingWhiteList + " " + newIPAddress
updatedString := re.ReplaceAllString(originalString, "${1}"+newWhiteList)
err = ioutil.WriteFile(serviceFilePath, []byte(updatedString), 0644)
if err != nil {
fmt.Println("Error writing file:", err)
return err
}
if err := exec.Command("systemctl", "daemon-reload").Run(); err != nil {
return err
}
if err := exec.Command("systemctl", "restart", "caddy.service").Run(); err != nil {
return err
}
fmt.Println("IP successfully bleached - ", newIPAddress)
return nil
} else {
fmt.Println("WHITE_LIST not found.")
return nil
}
}
func main() {
http.HandleFunc("/", getIP)
port := 50009
fmt.Printf("Server is running on port %d...\n", port)
err := http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
if err != nil {
fmt.Println("Error starting server:", err)
}
}