hibiscus/log.go

58 lines
1.3 KiB
Go
Raw Normal View History

2024-03-15 18:34:24 +03:00
package main
import (
"io"
2024-03-20 16:18:23 +03:00
"log/slog"
2024-03-15 18:34:24 +03:00
"net/http"
"os"
2024-03-15 19:22:22 +03:00
"strings"
2024-03-15 18:34:24 +03:00
"time"
)
2024-03-15 19:22:22 +03:00
// AppendLog adds the input string to the end of the log file with a timestamp
func appendLog(input string) error {
2024-03-15 20:20:33 +03:00
t := time.Now().Format("2006-01-02 15:04") // yyyy-mm-dd HH:MM
2024-03-20 16:18:23 +03:00
filename := "data/log.txt"
2024-03-15 18:34:24 +03:00
2024-03-20 16:18:23 +03:00
f, err := os.OpenFile(filename, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
2024-03-15 18:34:24 +03:00
if err != nil {
2024-03-20 16:18:23 +03:00
slog.Error("error opening/making file",
"error", err,
"file", filename)
2024-03-15 18:34:24 +03:00
return err
}
2024-03-15 19:22:22 +03:00
input = strings.Replace(input, "\n", "", -1) // Remove newlines to maintain structure
2024-03-15 18:34:24 +03:00
if _, err := f.Write([]byte(t + " | " + input + "\n")); err != nil {
2024-03-20 16:18:23 +03:00
slog.Error("error appending to file",
"error", err,
"file", filename)
2024-03-15 18:34:24 +03:00
return err
}
if err := f.Close(); err != nil {
2024-03-20 16:18:23 +03:00
slog.Error("error closing file",
"error", err,
"file", filename)
2024-03-15 18:34:24 +03:00
return err
}
return nil
}
func PostLog(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(r.Body)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("error reading body"))
return
}
2024-03-15 19:22:22 +03:00
err = appendLog(string(body))
2024-03-15 18:34:24 +03:00
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("error appending to log"))
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte("appended to log"))
}