diff options
-rw-r--r-- | main.go | 36 |
1 files changed, 35 insertions, 1 deletions
@@ -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 + }) +} |