hibiscus/files.go

74 lines
1.8 KiB
Go
Raw Normal View History

2024-03-15 18:34:24 +03:00
package main
import (
2024-03-30 14:33:39 +03:00
"bytes"
"errors"
2024-03-20 16:18:23 +03:00
"log/slog"
2024-03-15 18:34:24 +03:00
"os"
2024-03-18 20:04:14 +03:00
"path"
2024-03-15 18:34:24 +03:00
"path/filepath"
"strings"
2024-03-18 15:50:20 +03:00
"time"
2024-03-15 18:34:24 +03:00
)
// ReadFile returns raw contents of a file
func ReadFile(filename string) ([]byte, error) {
2024-03-18 20:04:14 +03:00
filename = "data/" + path.Clean(filename) + ".txt" // Does this sanitize the path?
2024-03-15 19:22:22 +03:00
2024-03-18 20:04:14 +03:00
if _, err := os.Stat(filename); errors.Is(err, os.ErrNotExist) {
return nil, err
2024-03-15 18:34:24 +03:00
}
2024-03-18 20:04:14 +03:00
fileContents, err := os.ReadFile(filename)
2024-03-15 18:34:24 +03:00
if err != nil {
2024-03-20 16:18:23 +03:00
slog.Error("error reading file",
"error", err,
"file", filename)
return nil, err
2024-03-15 18:34:24 +03:00
}
return fileContents, nil
2024-03-15 18:34:24 +03:00
}
// SaveFile Writes request's contents to a file
func SaveFile(filename string, contents []byte) error {
2024-03-20 16:18:23 +03:00
filename = "data/" + filename + ".txt"
2024-03-30 14:33:39 +03:00
f, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 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)
return err
2024-03-15 18:34:24 +03:00
}
2024-03-30 14:33:39 +03:00
if _, err := f.Write(bytes.TrimSpace(contents)); err != nil {
2024-03-20 16:18:23 +03:00
slog.Error("error writing to file",
"error", err,
"file", filename)
return err
2024-03-15 18:34:24 +03:00
}
return nil
2024-03-15 18:34:24 +03:00
}
// ListFiles returns slice of filenames in a directory without extensions or path
func ListFiles(directory string) ([]string, error) {
filenames, err := filepath.Glob("data/" + directory + "/*.txt")
2024-03-15 18:34:24 +03:00
if err != nil {
return nil, err
2024-03-15 18:34:24 +03:00
}
for i, file := range filenames {
file, _ := strings.CutSuffix(filepath.Base(file), filepath.Ext(file))
filenames[i] = file
}
return filenames, nil
2024-03-15 18:34:24 +03:00
}
2024-03-18 15:50:20 +03:00
// ReadToday runs ReadFile with today's date as filename
func ReadToday() ([]byte, error) {
2024-04-14 11:45:42 +03:00
return ReadFile("day/" + time.Now().In(Cfg.Timezone).Format(time.DateOnly))
2024-03-18 20:04:14 +03:00
}
// SaveToday runs SaveFile with today's date as filename
func SaveToday(contents []byte) error {
2024-04-14 11:45:42 +03:00
return SaveFile("day/"+time.Now().In(Cfg.Timezone).Format(time.DateOnly), contents)
2024-03-18 15:50:20 +03:00
}