hibiscus/log.go

51 lines
1.1 KiB
Go
Raw Normal View History

2024-03-15 18:34:24 +03:00
package main
import (
"fmt"
"io"
"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-15 18:34:24 +03:00
f, err := os.OpenFile("./data/log.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
fmt.Println("Error opening/making file")
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 {
fmt.Println("Error appending to the file")
return err
}
if err := f.Close(); err != nil {
fmt.Println("Error closing the file")
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"))
}