Skip to content

Commit

Permalink
Add TLS serving support
Browse files Browse the repository at this point in the history
Signed-off-by: Joe Beda <[email protected]>
  • Loading branch information
jbeda committed Mar 19, 2017
1 parent 9d924e1 commit 79d8d94
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
29 changes: 27 additions & 2 deletions pkg/app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import (
"net/http"
"net/http/httputil"
"os"
"path/filepath"
"strings"

"github.com/jbeda/kuard/pkg/debugprobe"
Expand Down Expand Up @@ -93,9 +94,33 @@ func (k *App) rootHandler(w http.ResponseWriter, r *http.Request, _ httprouter.P
k.tg.Render(w, "index.html", k.getPageContext(r))
}

// Exists reports whether the named file or directory exists.
func fileExists(name string) bool {
if _, err := os.Stat(name); err != nil {
if os.IsNotExist(err) {
return false
}
}
return true
}

func (k *App) Run() {
log.Printf("Serving on %v", k.c.ServeAddr)
log.Fatal(http.ListenAndServe(k.c.ServeAddr, loggingMiddleware(k.r)))
r := loggingMiddleware(k.r)

// Look to see if we can find TLS certs
certFile := filepath.Join(k.c.TLSDir, "kuard.crt")
keyFile := filepath.Join(k.c.TLSDir, "kuard.key")
if fileExists(certFile) && fileExists(keyFile) {
go func() {
log.Printf("Serving HTTPS on %v", k.c.TLSAddr)
log.Fatal(http.ListenAndServeTLS(k.c.TLSAddr, certFile, keyFile, r))
}()
} else {
log.Printf("Could not find certificates to serve TLS")
}

log.Printf("Serving on HTTP on %v", k.c.ServeAddr)
log.Fatal(http.ListenAndServe(k.c.ServeAddr, r))
}

func NewApp() *App {
Expand Down
6 changes: 6 additions & 0 deletions pkg/app/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ type Config struct {
Debug bool
DebugRootDir string `mapstructure:"debug-sitedata-dir"`
ServeAddr string `mapstructure:"address"`
TLSAddr string `mapstructure:"tls-address"`
TLSDir string `mapstructure:"tls-dir"`

KeyGen keygen.Config

Expand All @@ -46,6 +48,10 @@ func (k *App) BindConfig(v *viper.Viper, fs *pflag.FlagSet) {
v.BindPFlag("debug-sitedata-dir", fs.Lookup("debug-sitedata-dir"))
fs.String("address", ":8080", "The address to serve on")
v.BindPFlag("address", fs.Lookup("address"))
fs.String("tls-address", ":8443", "Address to serve TLS on if certs found.")
v.BindPFlag("tls-address", fs.Lookup("tls-address"))
fs.String("tls-dir", "/tls", "Directory to look to find TLS certs")
v.BindPFlag("tls-dir", fs.Lookup("tls-dir"))
}

func (k *App) LoadConfig(v *viper.Viper) {
Expand Down

0 comments on commit 79d8d94

Please sign in to comment.