refactor: refactoring of code

This commit is contained in:
Jonas Kaninda
2024-12-06 14:21:55 +01:00
parent 9016a9ec7a
commit afd4afc83b
19 changed files with 483 additions and 340 deletions

View File

@@ -1,78 +0,0 @@
// Package utils /
/*
MIT License
Copyright (c) 2023 Jonas Kaninda
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package utils
import (
"fmt"
"os"
"time"
)
func Info(msg string, args ...any) {
var currentTime = time.Now().Format("2006/01/02 15:04:05")
formattedMessage := fmt.Sprintf(msg, args...)
if len(args) == 0 {
fmt.Printf("%s INFO: %s\n", currentTime, msg)
} else {
fmt.Printf("%s INFO: %s\n", currentTime, formattedMessage)
}
}
// Warn warning message
func Warn(msg string, args ...any) {
var currentTime = time.Now().Format("2006/01/02 15:04:05")
formattedMessage := fmt.Sprintf(msg, args...)
if len(args) == 0 {
fmt.Printf("%s WARN: %s\n", currentTime, msg)
} else {
fmt.Printf("%s WARN: %s\n", currentTime, formattedMessage)
}
}
func Error(msg string, args ...any) {
var currentTime = time.Now().Format("2006/01/02 15:04:05")
formattedMessage := fmt.Sprintf(msg, args...)
if len(args) == 0 {
fmt.Printf("%s ERROR: %s\n", currentTime, msg)
} else {
fmt.Printf("%s ERROR: %s\n", currentTime, formattedMessage)
}
}
// Fatal logs an error message and exits the program
func Fatal(msg string, args ...any) {
var currentTime = time.Now().Format("2006/01/02 15:04:05")
// Fatal logs an error message and exits the program.
formattedMessage := fmt.Sprintf(msg, args...)
if len(args) == 0 {
fmt.Printf("%s ERROR: %s\n", currentTime, msg)
NotifyError(msg)
} else {
fmt.Printf("%s ERROR: %s\n", currentTime, formattedMessage)
NotifyError(formattedMessage)
}
os.Exit(1)
}

View File

@@ -1,20 +1,5 @@
package utils
import (
"bytes"
"crypto/tls"
"encoding/json"
"fmt"
"github.com/go-mail/mail"
"html/template"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"strings"
"time"
)
/*
MIT License
@@ -39,6 +24,22 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import (
"bytes"
"crypto/tls"
"encoding/json"
"fmt"
"github.com/go-mail/mail"
"github.com/jkaninda/mysql-bkup/pkg/logger"
"html/template"
"io"
"net/http"
"os"
"path/filepath"
"strings"
"time"
)
func parseTemplate[T any](data T, fileName string) (string, error) {
// Open the file
tmpl, err := template.ParseFiles(filepath.Join(templatePath, fileName))
@@ -55,7 +56,7 @@ func parseTemplate[T any](data T, fileName string) (string, error) {
}
func SendEmail(subject, body string) error {
Info("Start sending email notification....")
logger.Info("Start sending email notification....")
config := loadMailConfig()
emails := strings.Split(config.MailTo, ",")
m := mail.NewMessage()
@@ -67,16 +68,16 @@ func SendEmail(subject, body string) error {
d.TLSConfig = &tls.Config{InsecureSkipVerify: config.SkipTls}
if err := d.DialAndSend(m); err != nil {
Error("Error could not send email : %v", err)
logger.Error("Error could not send email : %v", err)
return err
}
Info("Email notification has been sent")
logger.Info("Email notification has been sent")
return nil
}
func sendMessage(msg string) error {
Info("Sending Telegram notification... ")
logger.Info("Sending Telegram notification... ")
chatId := os.Getenv("TG_CHAT_ID")
body, _ := json.Marshal(map[string]string{
"chat_id": chatId,
@@ -96,11 +97,11 @@ func sendMessage(msg string) error {
}
code := response.StatusCode
if code == 200 {
Info("Telegram notification has been sent")
logger.Info("Telegram notification has been sent")
return nil
} else {
body, _ := ioutil.ReadAll(response.Body)
Error("Error could not send message, error: %s", string(body))
body, _ := io.ReadAll(response.Body)
logger.Error("Error could not send message, error: %s", string(body))
return fmt.Errorf("error could not send message %s", string(body))
}
@@ -120,29 +121,29 @@ func NotifySuccess(notificationData *NotificationData) {
"MAIL_TO",
}
//Email notification
// Email notification
err := CheckEnvVars(mailVars)
if err == nil {
body, err := parseTemplate(*notificationData, "email.tmpl")
if err != nil {
Error("Could not parse email template: %v", err)
logger.Error("Could not parse email template: %v", err)
}
err = SendEmail(fmt.Sprintf("✅ Database Backup Notification %s", notificationData.Database), body)
if err != nil {
Error("Could not send email: %v", err)
logger.Error("Could not send email: %v", err)
}
}
//Telegram notification
// Telegram notification
err = CheckEnvVars(vars)
if err == nil {
message, err := parseTemplate(*notificationData, "telegram.tmpl")
if err != nil {
Error("Could not parse telegram template: %v", err)
logger.Error("Could not parse telegram template: %v", err)
}
err = sendMessage(message)
if err != nil {
Error("Could not send Telegram message: %v", err)
logger.Error("Could not send Telegram message: %v", err)
}
}
}
@@ -160,7 +161,7 @@ func NotifyError(error string) {
"MAIL_TO",
}
//Email notification
// Email notification
err := CheckEnvVars(mailVars)
if err == nil {
body, err := parseTemplate(ErrorMessage{
@@ -169,14 +170,14 @@ func NotifyError(error string) {
BackupReference: os.Getenv("BACKUP_REFERENCE"),
}, "email-error.tmpl")
if err != nil {
Error("Could not parse error template: %v", err)
logger.Error("Could not parse error template: %v", err)
}
err = SendEmail(fmt.Sprintf("🔴 Urgent: Database Backup Failure Notification"), body)
err = SendEmail("🔴 Urgent: Database Backup Failure Notification", body)
if err != nil {
Error("Could not send email: %v", err)
logger.Error("Could not send email: %v", err)
}
}
//Telegram notification
// Telegram notification
err = CheckEnvVars(vars)
if err == nil {
message, err := parseTemplate(ErrorMessage{
@@ -185,13 +186,13 @@ func NotifyError(error string) {
BackupReference: os.Getenv("BACKUP_REFERENCE"),
}, "telegram-error.tmpl")
if err != nil {
Error("Could not parse error template: %v", err)
logger.Error("Could not parse error template: %v", err)
}
err = sendMessage(message)
if err != nil {
Error("Could not send telegram message: %v", err)
logger.Error("Could not send telegram message: %v", err)
}
}
}

View File

@@ -26,6 +26,7 @@ package utils
import (
"fmt"
"github.com/jkaninda/mysql-bkup/pkg/logger"
"github.com/robfig/cron/v3"
"github.com/spf13/cobra"
"io"
@@ -35,6 +36,8 @@ import (
"time"
)
var Version = "development"
// FileExists checks if the file does exist
func FileExists(filename string) bool {
info, err := os.Stat(filename)
@@ -49,7 +52,13 @@ func WriteToFile(filePath, content string) error {
if err != nil {
return err
}
defer file.Close()
defer func(file *os.File) {
err := file.Close()
if err != nil {
return
}
}(file)
_, err = file.WriteString(content)
return err
@@ -67,14 +76,25 @@ func CopyFile(src, dst string) error {
if err != nil {
return fmt.Errorf("failed to open source file: %v", err)
}
defer sourceFile.Close()
defer func(sourceFile *os.File) {
err := sourceFile.Close()
if err != nil {
return
}
}(sourceFile)
// Create the destination file
destinationFile, err := os.Create(dst)
if err != nil {
return fmt.Errorf("failed to create destination file: %v", err)
}
defer destinationFile.Close()
defer func(destinationFile *os.File) {
err := destinationFile.Close()
if err != nil {
return
}
}(destinationFile)
// Copy the content from source to destination
_, err = io.Copy(destinationFile, sourceFile)
@@ -92,7 +112,7 @@ func CopyFile(src, dst string) error {
}
func ChangePermission(filePath string, mod int) {
if err := os.Chmod(filePath, fs.FileMode(mod)); err != nil {
Fatal("Error changing permissions of %s: %v\n", filePath, err)
logger.Fatal("Error changing permissions of %s: %v\n", filePath, err)
}
}
@@ -101,7 +121,12 @@ func IsDirEmpty(name string) (bool, error) {
if err != nil {
return false, err
}
defer f.Close()
defer func(f *os.File) {
err := f.Close()
if err != nil {
return
}
}(f)
_, err = f.Readdirnames(1)
if err == nil {
@@ -149,7 +174,7 @@ func GetEnvVariable(envName, oldEnvName string) string {
if err != nil {
return value
}
Warn("%s is deprecated, please use %s instead! ", oldEnvName, envName)
logger.Warn("%s is deprecated, please use %s instead! ", oldEnvName, envName)
}
}
return value
@@ -196,10 +221,11 @@ func GetIntEnv(envName string) int {
}
ret, err := strconv.Atoi(val)
if err != nil {
Error("Error: %v", err)
logger.Error("Error: %v", err)
}
return ret
}
func EnvWithDefault(envName string, defaultValue string) string {
value := os.Getenv(envName)
if value == "" {
@@ -220,13 +246,12 @@ func CronNextTime(cronExpr string) time.Time {
// Parse the cron expression
schedule, err := cron.ParseStandard(cronExpr)
if err != nil {
Error("Error parsing cron expression: %s", err)
logger.Error("Error parsing cron expression: %s", err)
return time.Time{}
}
// Get the current time
now := time.Now()
// Get the next scheduled time
next := schedule.Next(now)
//Info("The next scheduled time is: %v\n", next)
return next
}