From 5b4822967312608befb2ae637dbf6fd3d5b35142 Mon Sep 17 00:00:00 2001 From: Will McCutchen <will@mccutch.org> Date: Thu, 3 Oct 2019 12:22:06 -0700 Subject: [PATCH] Simplify https cert handling --- cmd/maincmd/main.go | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/cmd/maincmd/main.go b/cmd/maincmd/main.go index 5334aac..ebe53a0 100644 --- a/cmd/maincmd/main.go +++ b/cmd/maincmd/main.go @@ -2,7 +2,6 @@ package maincmd import ( "context" - "crypto/tls" "flag" "fmt" "log" @@ -78,6 +77,16 @@ func Main() { httpsKeyFile = os.Getenv("HTTPS_KEY_FILE") } + var serveTLS bool + if httpsCertFile != "" || httpsKeyFile != "" { + serveTLS = true + if httpsCertFile == "" || httpsKeyFile == "" { + fmt.Fprintf(os.Stderr, "Error: https cert and key must both be provided\n\n") + flag.Usage() + os.Exit(1) + } + } + logger := log.New(os.Stderr, "", 0) // A hacky log helper function to ensure that shutdown messages are @@ -128,16 +137,9 @@ func Main() { }() var listenErr error - if httpsCertFile != "" && httpsKeyFile != "" { - cert, err := tls.LoadX509KeyPair(httpsCertFile, httpsKeyFile) - if err != nil { - logger.Fatalf("failed to generate https key pair: %s", err) - } - server.TLSConfig = &tls.Config{ - Certificates: []tls.Certificate{cert}, - } + if serveTLS { serverLog("go-httpbin listening on https://%s", listenAddr) - listenErr = server.ListenAndServeTLS("", "") + listenErr = server.ListenAndServeTLS(httpsCertFile, httpsKeyFile) } else { serverLog("go-httpbin listening on http://%s", listenAddr) listenErr = server.ListenAndServe() -- GitLab