refactored to use filepath.Join(), better error logging

This commit is contained in:
uan
2025-08-08 13:25:13 +02:00
parent c721702b4a
commit 3746cff406
3 changed files with 31 additions and 38 deletions

View File

@@ -3,6 +3,7 @@ package miniws
import ( import (
"fmt" "fmt"
"os" "os"
"path/filepath"
"github.com/google/uuid" "github.com/google/uuid"
) )
@@ -28,9 +29,9 @@ func NewLogger(logFolder_ string, maxLogBytes_ int64) *Logger {
} }
// returns error != nil // returns error != nil
func (l *Logger) logIfError(err error) bool { func (l *Logger) logIfError(err error, filePath string) bool {
if err != nil { if err != nil {
l.logError(err.Error()) l.logError(filePath + " " + err.Error())
return true return true
} }
return false return false
@@ -52,10 +53,11 @@ func (l *Logger) logError(str string) {
l.writeToLogFileAndRenameIfBig(FILENAME_ERRORLOG, str+"\n") l.writeToLogFileAndRenameIfBig(FILENAME_ERRORLOG, str+"\n")
} }
func (l *Logger) writeToLogFileAndRenameIfBig(filename, content string) { func (l *Logger) writeToLogFileAndRenameIfBig(fileName, content string) {
file, err := os.OpenFile(ensureSlashSuffix(l.logFolder)+filename, FLAGS_LOG_OPEN, PERMS_LOG_OPEN) fullPath := filepath.Join(l.logFolder, fileName)
file, err := os.OpenFile(fullPath, FLAGS_LOG_OPEN, PERMS_LOG_OPEN)
if l.logIfError(err) { if l.logIfError(err, fullPath) {
return return
} }
@@ -64,27 +66,27 @@ func (l *Logger) writeToLogFileAndRenameIfBig(filename, content string) {
fileinfo, err := file.Stat() fileinfo, err := file.Stat()
if l.logIfError(err) { if l.logIfError(err, fullPath) {
return return
} }
if fileinfo.Size() > l.maxLogBytes { if fileinfo.Size() > l.maxLogBytes {
var renamedFiledPath string = ensureSlashSuffix(l.logFolder) + fileinfo.Name() + "." + uuid.NewString() var renamedFiledPath string = fullPath + "." + uuid.NewString()
err_rename := os.Rename( err_rename := os.Rename(
ensureSlashSuffix(l.logFolder)+fileinfo.Name(), fullPath,
renamedFiledPath, renamedFiledPath,
) )
if l.logIfError(err_rename) { if l.logIfError(err_rename, fullPath) {
return return
} }
compress := &compress{} compress := &compress{}
err_compress := compress.CompressFile(renamedFiledPath) err_compress := compress.CompressFile(renamedFiledPath)
if l.logIfError(err_compress) { if l.logIfError(err_compress, renamedFiledPath) {
return return
} }

View File

@@ -2,7 +2,6 @@ package miniws
import ( import (
"strconv" "strconv"
"strings"
) )
func getHttpVersionString(major, minor int) string { func getHttpVersionString(major, minor int) string {
@@ -15,7 +14,3 @@ func getOrDash(str string) string {
} }
return str return str
} }
func ensureSlashSuffix(str string) string {
return strings.TrimSuffix(str, "/") + "/"
}

View File

@@ -60,31 +60,32 @@ func (ws *WebServer) Run() {
http.ListenAndServe(":"+strconv.Itoa(ws.port), nil) http.ListenAndServe(":"+strconv.Itoa(ws.port), nil)
} }
func (ws *WebServer) parseFilterPanics(filename string) (FilterMode, []string) { func (ws *WebServer) parseFilterPanics(fileName string) (FilterMode, []string) {
filterMode := FILTER_MODE_BLACKLIST filterMode := FILTER_MODE_BLACKLIST
filter := make([]string, 0) filter := make([]string, 0)
os.Mkdir(ws.configFolder, PERMS_MKDIR) os.Mkdir(ws.configFolder, PERMS_MKDIR)
fileinfo, err := os.Stat(ensureSlashSuffix(ws.configFolder) + filename) fileinfo, err := os.Stat(filepath.Join(ws.configFolder, fileName))
fullPath := filepath.Join(ws.configFolder, fileName)
if errors.Is(err, os.ErrNotExist) { if errors.Is(err, os.ErrNotExist) {
os.Create(ensureSlashSuffix(ws.configFolder) + filename) os.Create(fullPath)
fileinfo, err = os.Stat(ensureSlashSuffix(ws.configFolder) + filename) fileinfo, err = os.Stat(fullPath)
} }
if err != nil { if err != nil {
panic("Error opening " + filename + ": " + err.Error()) panic("Error opening " + fileName + ": " + err.Error())
} }
if fileinfo.Size() == 0 { // empty config if fileinfo.Size() == 0 { // empty config
return filterMode, filter return filterMode, filter
} }
filterContent, err := os.ReadFile(ensureSlashSuffix(ws.configFolder) + filename) filterContent, err := os.ReadFile(fullPath)
if ws.logger.logIfError(err) { if ws.logger.logIfError(err, fullPath) {
panic("Error reading " + filename + ": " + err.Error()) panic("Error reading " + fileName + ": " + err.Error())
} }
filterLines := strings.Split(string(filterContent), "\n") filterLines := strings.Split(string(filterContent), "\n")
@@ -96,7 +97,7 @@ func (ws *WebServer) parseFilterPanics(filename string) (FilterMode, []string) {
case "deny": case "deny":
filterMode = FILTER_MODE_BLACKLIST filterMode = FILTER_MODE_BLACKLIST
default: default:
panic("invalid filter mode for " + filename + ": use allow|deny") panic("invalid filter mode for " + fileName + ": use allow|deny")
} }
filter = filterLines[1:] filter = filterLines[1:]
@@ -135,27 +136,22 @@ func (ws *WebServer) isUserAgentValid(userAgent string) bool {
// IMPORTANT: remember to close the file after use!!!! fetchFile doesn't // IMPORTANT: remember to close the file after use!!!! fetchFile doesn't
// do it for you for obvious reasons // do it for you for obvious reasons
func (ws *WebServer) fetchFile(filepath string) (*os.File, error) { func (ws *WebServer) fetchFile(filepath string) (*os.File, error) {
return os.OpenFile(ws._cleanFilepath(filepath), os.O_RDONLY, 0) return os.OpenFile(ws._addIndexIfDir(filepath), os.O_RDONLY, 0)
} }
func (ws *WebServer) fetchStat(filepath string) (os.FileInfo, error) { func (ws *WebServer) fetchStat(filepath string) (os.FileInfo, error) {
clean_filepath := ws._cleanFilepath(filepath) return os.Stat(ws._addIndexIfDir(filepath))
return os.Stat(clean_filepath)
} }
func (ws *WebServer) _cleanFilepath(filepath string) string { func (ws *WebServer) _addIndexIfDir(filePath string) string {
if filepath == "/" { fileinfo, err := os.Stat(filePath)
filepath = "." if ws.logger.logIfError(err, filePath) {
}
fileinfo, err := os.Stat(filepath)
if err != nil {
ws.logger.logError(err.Error())
return "" return ""
} }
if fileinfo.IsDir() { if fileinfo.IsDir() {
filepath += "index.html" filePath += "/index.html"
} }
return filepath return filePath
} }
func (ws *WebServer) get(writer http.ResponseWriter, req *http.Request) { func (ws *WebServer) get(writer http.ResponseWriter, req *http.Request) {
@@ -179,14 +175,14 @@ func (ws *WebServer) get(writer http.ResponseWriter, req *http.Request) {
return return
} }
fileToFetch := ensureSlashSuffix(ws.wwwFolder) + strings.TrimPrefix(req.URL.Path, "/") fileToFetch := filepath.Join(ws.wwwFolder, req.URL.Path)
fetchedFile, fetchErr := ws.fetchFile(fileToFetch) fetchedFile, fetchErr := ws.fetchFile(fileToFetch)
fetchedFileStat, _ := fetchedFile.Stat() fetchedFileStat, _ := fetchedFile.Stat()
fetchedStat, _ := ws.fetchStat(fileToFetch) fetchedStat, _ := ws.fetchStat(fileToFetch)
sentBytes := int64(0) sentBytes := int64(0)
if ws.logger.logIfError(fetchErr) { if ws.logger.logIfError(fetchErr, fileToFetch) {
respStatusCode = http.StatusNotFound respStatusCode = http.StatusNotFound
writer.WriteHeader(respStatusCode) writer.WriteHeader(respStatusCode)
} else { } else {