Improve log a bit

This commit is contained in:
Andrew-71 2024-03-15 19:22:22 +03:00
parent c5a5dbd80b
commit 6ad28b714b
4 changed files with 14 additions and 10 deletions

View file

@ -1,7 +1,8 @@
# 🌺 Hibiscus.txt
Simple plaintext journaling server. One file a day.
Simple plaintext diary.
## Features:
* Lack of features. No, really.
* Does one thing and does it... decently?
* Intention to eventually go dependency-less. Sorry chi, I still like you!

View file

@ -11,15 +11,15 @@ import (
"strings"
)
var DEFAULT_EXTENSION = "txt"
func GetFile(filename string, w http.ResponseWriter, r *http.Request) {
if _, err := os.Stat("data/" + filename + ".txt"); errors.Is(err, os.ErrNotExist) {
path := "data/" + filepath.Base(filename) + ".txt" // This should *theoretically* sanitize the string
if _, err := os.Stat(path); errors.Is(err, os.ErrNotExist) {
NotFound(w, r)
return
}
fileContents, err := os.ReadFile("data/" + filename + ".txt")
fileContents, err := os.ReadFile(path)
if err != nil {
http.Error(w, "error reading file", http.StatusInternalServerError)
return
@ -58,7 +58,7 @@ func PostFile(filename string, w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}
// ListFiles returns JSON of filenames in a directory without extensions or path
// ListFiles returns JSON list of filenames in a directory without extensions or path
func ListFiles(directory string, w http.ResponseWriter, r *http.Request) {
filenames, err := filepath.Glob("data/" + directory + "/*.txt")
if err != nil {

7
log.go
View file

@ -5,10 +5,12 @@ import (
"io"
"net/http"
"os"
"strings"
"time"
)
func AppendLog(input string) error {
// AppendLog adds the input string to the end of the log file with a timestamp
func appendLog(input string) error {
t := time.Now().Format("02-01-2006 15:04") // dd-mm-yyyy HH:MM
f, err := os.OpenFile("./data/log.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
@ -17,6 +19,7 @@ func AppendLog(input string) error {
return err
}
input = strings.Replace(input, "\n", "", -1) // Remove newlines to maintain structure
if _, err := f.Write([]byte(t + " | " + input + "\n")); err != nil {
fmt.Println("Error appending to the file")
return err
@ -35,7 +38,7 @@ func PostLog(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("error reading body"))
return
}
err = AppendLog(string(body))
err = appendLog(string(body))
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("error appending to log"))

View file

@ -1 +1 @@
curl -XPOST -d 'need to \n remove newlines \n' -u 'test:pass' 'localhost:7101/log'
curl -XPOST -d "test" -eu 'test:pass' 'localhost:7101/api/log'