From adf5ba0e3e0507f6089c811256ce33f6a2972162 Mon Sep 17 00:00:00 2001 From: KJHJason Date: Mon, 20 May 2024 21:02:34 +0800 Subject: [PATCH] Removed panics from httpfuncs.go and logger.go --- httpfuncs/httpfuncs.go | 13 ++++-------- logger/log.go | 46 ++++++++++++++++++++++++++++-------------- 2 files changed, 35 insertions(+), 24 deletions(-) diff --git a/httpfuncs/httpfuncs.go b/httpfuncs/httpfuncs.go index 2e21e66..6b56642 100644 --- a/httpfuncs/httpfuncs.go +++ b/httpfuncs/httpfuncs.go @@ -22,16 +22,11 @@ func init() { "windows": "Windows NT 10.0; Win64; x64", } userAgentOS, ok := userAgent[runtime.GOOS] - if !ok { - panic( - fmt.Errorf( - "error %d: Failed to get user agent OS as your OS, %q, is not supported", - cdlerrors.OS_ERROR, - runtime.GOOS, - ), - ) + if !ok { // fallback to Windows + DEFAULT_USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36" + } else { + DEFAULT_USER_AGENT = fmt.Sprintf("Mozilla/5.0 (%s) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36", userAgentOS) } - DEFAULT_USER_AGENT = fmt.Sprintf("Mozilla/5.0 (%s) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36", userAgentOS) } // Returns a boolean value indicating whether the specified site supports HTTP/3 diff --git a/logger/log.go b/logger/log.go index bbe5782..34516e0 100644 --- a/logger/log.go +++ b/logger/log.go @@ -17,43 +17,59 @@ import ( const ( LOG_SUFFIX = "\n\n" - LOG_PERMS = 0644 + LOG_PERMS = 0644 // rw-r--r-- LOG_THRESHOLD = 15 * 24 * time.Hour ) var ( MainLogger Logger logFolder = filepath.Join(iofuncs.APP_PATH, "logs") - logFilePath = filepath.Join( - logFolder, - fmt.Sprintf( - "cultured_downloader-logic_v%s_%s.log", - constants.VERSION, - time.Now().Format("2006-01-02"), - ), - ) + logFilePath = filepath.Join(logFolder, getLogFileName()) ) -func InitLogger() { +func getLogFileName() string { + return fmt.Sprintf( + "cultured_downloader-logic_v%s_%s.log", + constants.VERSION, + time.Now().Format("2006-01-02"), + ) +} + +func init() { // create the logs directory if it does not exist os.MkdirAll(logFolder, LOG_PERMS) // will be opened throughout the program's runtime // hence, there is no need to call f.Close() at the end of this function + logFlags := os.O_WRONLY | os.O_CREATE | os.O_APPEND f, fileErr := os.OpenFile( logFilePath, - os.O_WRONLY|os.O_CREATE|os.O_APPEND, - 0666, + logFlags, + LOG_PERMS, ) - if fileErr != nil { + if fileErr == nil { + MainLogger = NewLogger(f) + } else { fileErr = fmt.Errorf( "error opening log file: %w\nlog file path: %s", fileErr, logFilePath, ) - panic(fileErr) + + // fallback to cwd if the logs directory cannot be created + var fallbackFileErr error + f, fallbackFileErr = os.OpenFile( + getLogFileName(), + logFlags, + LOG_PERMS, + ) + if fallbackFileErr != nil { + panic(fileErr) + } + + MainLogger = NewLogger(f) + LogError(fileErr, ERROR) } - MainLogger = NewLogger(f) DeleteEmptyAndOldLogs() }