From 38d1dfb2d41699ee71108c421ef624e1eca5c878 Mon Sep 17 00:00:00 2001 From: Julien Riou Date: Fri, 5 Nov 2021 08:16:36 +0100 Subject: [PATCH] fix: Use template files on disk (#4) Signed-off-by: Julien Riou --- notification.go | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/notification.go b/notification.go index 8d9eeff..6cf6a17 100644 --- a/notification.go +++ b/notification.go @@ -3,6 +3,7 @@ package main import ( "bytes" "embed" + "errors" "fmt" "os" "path" @@ -79,14 +80,6 @@ func (t *TelegramNotifier) sendMessage(message string) error { // formatMessage to create a message with a template file name (either embeded or on disk) func (t *TelegramNotifier) formatMessage(templateFileName string, attachment interface{}) (message string, err error) { - // Deduce if template file is embeded or is a file on disk - embeded := true - if _, err = os.Stat(templateFileName); os.IsExist(err) { - embeded = false - } - // Reinitialize the error because it was only used for the test - err = nil - // Create template templateName := path.Base(templateFileName) templateFunctions := template.FuncMap{ @@ -99,12 +92,12 @@ func (t *TelegramNotifier) formatMessage(templateFileName string, attachment int tmpl := template.New(templateName).Funcs(templateFunctions) // Parse template - if embeded { - log.Debugf("Parsing embeded template file %s", templateFileName) - tmpl, err = tmpl.ParseFS(templateFiles, templateFileName) - } else { + if fileExists(templateFileName) { log.Debugf("Parsing template file %s", templateFileName) tmpl, err = tmpl.ParseFiles(templateFileName) + } else { + log.Debugf("Parsing embeded template file %s", templateFileName) + tmpl, err = tmpl.ParseFS(templateFiles, templateFileName) } if err != nil { return "", fmt.Errorf("parse failed: %v", err) @@ -122,6 +115,12 @@ func (t *TelegramNotifier) formatMessage(templateFileName string, attachment int return message, nil } +// isFileTemplate returns true when the filename is a real file on the filesystem +func fileExists(filename string) bool { + _, err := os.Stat(filename) + return !errors.Is(err, os.ErrNotExist) +} + // NotifyBalance to format and send a notification when the unpaid balance has changed // Implements the Notifier interface func (t *TelegramNotifier) NotifyBalance(miner Miner) (err error) {