Browse Source

web: log an error if loading a required template fails

We used template.Must that panics if an error happen but the error is
visible only if sftpgo is started in an interactive way

Fixes #82
Nicola Murino 5 years ago
parent
commit
3ffddcba92
2 changed files with 17 additions and 4 deletions
  1. 4 4
      httpd/web.go
  2. 13 0
      utils/utils.go

+ 4 - 4
httpd/web.go

@@ -98,10 +98,10 @@ func loadTemplates(templatesPath string) {
 		filepath.Join(templatesPath, templateBase),
 		filepath.Join(templatesPath, templateMessage),
 	}
-	usersTmpl := template.Must(template.ParseFiles(usersPaths...))
-	userTmpl := template.Must(template.ParseFiles(userPaths...))
-	connectionsTmpl := template.Must(template.ParseFiles(connectionsPaths...))
-	messageTmpl := template.Must(template.ParseFiles(messagePath...))
+	usersTmpl := utils.LoadTemplate(template.ParseFiles(usersPaths...))
+	userTmpl := utils.LoadTemplate(template.ParseFiles(userPaths...))
+	connectionsTmpl := utils.LoadTemplate(template.ParseFiles(connectionsPaths...))
+	messageTmpl := utils.LoadTemplate(template.ParseFiles(messagePath...))
 
 	templates[templateUsers] = usersTmpl
 	templates[templateUser] = userTmpl

+ 13 - 0
utils/utils.go

@@ -13,6 +13,7 @@ import (
 	"encoding/pem"
 	"errors"
 	"fmt"
+	"html/template"
 	"io"
 	"io/ioutil"
 	"net"
@@ -22,6 +23,7 @@ import (
 	"strings"
 	"time"
 
+	"github.com/drakkan/sftpgo/logger"
 	"golang.org/x/crypto/ssh"
 )
 
@@ -275,3 +277,14 @@ func CleanSFTPPath(p string) string {
 	}
 	return path.Clean(sftpPath)
 }
+
+// LoadTemplate wraps a call to a function returning (*Template, error)
+// it is just like template.Must but it writes a log before exiting
+func LoadTemplate(t *template.Template, err error) *template.Template {
+	if err != nil {
+		logger.ErrorToConsole("error loading required template: %v", err)
+		logger.Error(logSender, "", "error loading required template: %v", err)
+		panic(err)
+	}
+	return t
+}