summaryrefslogtreecommitdiff
path: root/main.go
diff options
context:
space:
mode:
authorRobby Zambito <contact@robbyzambito.me>2025-08-05 21:45:23 -0400
committerRobby Zambito <contact@robbyzambito.me>2025-08-06 01:05:04 -0400
commite28a4383d8c33724b90b8a433fe87f2e816652f9 (patch)
tree6c768e9319436258c3b7cfa0b211011123222e59 /main.go
parenta3f0b458370b3f0b00ce2897053e5e4a4a6add27 (diff)
Log access as json
Redact client IPs
Diffstat (limited to 'main.go')
-rw-r--r--main.go36
1 files changed, 35 insertions, 1 deletions
diff --git a/main.go b/main.go
index f56cda1..83e11b0 100644
--- a/main.go
+++ b/main.go
@@ -1,13 +1,24 @@
package main
import (
+ "encoding/json"
"fmt"
"net/http"
+ "net"
+ "regexp"
"strings"
+ "time"
)
const log_length = 100
+type accessLog struct {
+ ClientAddr string `json:"clientAddr"`
+ RequestedPath string `json:"requestedPath"`
+ RequestTime time.Time `json:"requestTime"`
+ HttpMethod string `json:"httpMethod"`
+}
+
func main() {
fs := http.FileServer(http.Dir("static"))
@@ -16,7 +27,13 @@ func main() {
// Define a handler function for the root path
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
- addRotLog(&logs, &n, fmt.Sprintf("Accessed %s", r.URL.Path, x, n))
+ jsonData, _ := json.Marshal(accessLog{
+ ClientAddr: RedactIP(r.RemoteAddr),
+ RequestedPath: r.URL.Path,
+ RequestTime: time.Now().UTC(),
+ HttpMethod: r.Method,
+ })
+ addRotLog(&logs, &n, fmt.Sprintf("%s", string(jsonData)))
// Serve the index.html file from the static directory
http.StripPrefix("/", fs).ServeHTTP(w, r)
})
@@ -60,3 +77,20 @@ func addRotLog(logs *[log_length]string, last *int, value string) {
}
}
}
+
+// RedactIP partially redacts an IP address by replacing the last octet with 'xxx'
+func RedactIP(input string) string {
+ ipRegex := `\b(?:\d{1,3}\.){3}\d{1,3}\b`
+ re := regexp.MustCompile(ipRegex)
+
+ return re.ReplaceAllStringFunc(input, func(match string) string {
+ if ip := net.ParseIP(match); ip != nil {
+ parts := strings.Split(match, ".")
+ if len(parts) == 4 {
+ parts[3] = "XXX"
+ return strings.Join(parts, ".")
+ }
+ }
+ return match
+ })
+}