From b09881ac7e43ac87c0ab226878ea41b468928c8a Mon Sep 17 00:00:00 2001 From: Christoph Petrausch Date: Wed, 8 Jul 2020 11:42:49 +0200 Subject: [PATCH] Fix the loading of the TLS files Don't error if the file is not specified. Fixes #36. --- main.go | 46 +++++++++++++++++++++++++++++----------------- 1 file changed, 29 insertions(+), 17 deletions(-) diff --git a/main.go b/main.go index ed930f1..43897b9 100644 --- a/main.go +++ b/main.go @@ -82,6 +82,7 @@ func fileExists(filename string) bool { return !info.IsDir() } +// An error is returned of the given TLS configuration is invalid. func validateTLSFiles(argCafile, argKey, argCert string) error { if len(argCafile) > 0 { if !fileExists(argCafile) { @@ -109,6 +110,18 @@ func validateTLSFiles(argCafile, argKey, argCert string) error { return nil } +// loadTLSFile loads the given file. If the filename is empty neither data nor an error is returned. +func loadTLSFile(fileName string) ([]byte, error) { + if len(fileName) > 0 { + data, err := ioutil.ReadFile(fileName) + if err != nil { + return nil, fmt.Errorf("failed to load TLS file: %s: %w", fileName, err) + } + return data, nil + } + return nil, nil +} + func main() { flag.Parse() @@ -185,23 +198,22 @@ func main() { if err := validateTLSFiles(*argCafile, *argKey, *argCert); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) - } else { - var err error - ca, err = ioutil.ReadFile(*argCafile) - if err != nil { - fmt.Fprintln(os.Stderr, err) - os.Exit(1) - } - cert, err = ioutil.ReadFile(*argCert) - if err != nil { - fmt.Fprintln(os.Stderr, err) - os.Exit(1) - } - key, err = ioutil.ReadFile(*argKey) - if err != nil { - fmt.Fprintln(os.Stderr, err) - os.Exit(1) - } + } + + ca, err = loadTLSFile(*argCafile) + if err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } + cert, err = loadTLSFile(*argCert) + if err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } + key, err = loadTLSFile(*argKey) + if err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) } signalChan := make(chan os.Signal, 1)