single-mode
This commit is contained in:
93
main.go
Normal file
93
main.go
Normal file
@@ -0,0 +1,93 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
var (
|
||||
ctx = context.Background()
|
||||
redisClient *redis.Client
|
||||
hashName = "bl:sendnrw"
|
||||
)
|
||||
|
||||
func main() {
|
||||
// Redis Client initialisieren
|
||||
redisClient = redis.NewClient(&redis.Options{
|
||||
Addr: "10.10.5.249:6379", // ggf. anpassen
|
||||
Password: "", // falls Passwort benötigt wird
|
||||
DB: 0, // Standard DB
|
||||
})
|
||||
|
||||
// Testverbindung
|
||||
if err := redisClient.Ping(ctx).Err(); err != nil {
|
||||
log.Fatalf("Keine Verbindung zu Redis: %v", err)
|
||||
}
|
||||
|
||||
http.HandleFunc("/", logIPHandler)
|
||||
|
||||
log.Println("Server startet auf :8082")
|
||||
if err := http.ListenAndServe(":8082", nil); err != nil {
|
||||
log.Fatal("ListenAndServe: ", err)
|
||||
}
|
||||
}
|
||||
|
||||
func logIPHandler(w http.ResponseWriter, r *http.Request) {
|
||||
ip := getClientIP(r)
|
||||
if ip == "" {
|
||||
http.Error(w, "Ungültige IP", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
ipKey := ip + "/32"
|
||||
|
||||
// IP in Redis Hash speichern
|
||||
err := redisClient.HSet(ctx, hashName, ipKey, 1).Err()
|
||||
if err != nil {
|
||||
log.Printf("Fehler beim Schreiben in Redis: %v", err)
|
||||
http.Error(w, "Interner Fehler", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
log.Printf("IP %s in Redis gespeichert", ipKey)
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte("IP erfasst: " + ipKey + "\n"))
|
||||
}
|
||||
|
||||
func getClientIP(r *http.Request) string {
|
||||
// X-Forwarded-For prüfen
|
||||
xff := r.Header.Get("X-Forwarded-For")
|
||||
if xff != "" {
|
||||
parts := strings.Split(xff, ",")
|
||||
ip := strings.TrimSpace(parts[0])
|
||||
if isValidIP(ip) {
|
||||
return ip
|
||||
}
|
||||
}
|
||||
|
||||
// X-Real-IP prüfen
|
||||
xrip := r.Header.Get("X-Real-Ip")
|
||||
if xrip != "" && isValidIP(xrip) {
|
||||
return xrip
|
||||
}
|
||||
|
||||
// RemoteAddr als Fallback
|
||||
host, _, err := net.SplitHostPort(r.RemoteAddr)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
if isValidIP(host) {
|
||||
return host
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func isValidIP(ip string) bool {
|
||||
return net.ParseIP(ip) != nil
|
||||
}
|
Reference in New Issue
Block a user