add support for serving TLS

This commit is contained in:
Stephen McQuay 2017-02-06 21:32:48 -08:00
parent 5ba960613c
commit c13c59650e
No known key found for this signature in database
GPG Key ID: 1ABF428F71BAFC3D
2 changed files with 31 additions and 4 deletions

View File

@ -14,4 +14,7 @@ use:
# allow serving hidden files/dirs
servedir -hidden
# serve https, with http redirect
TLS_CERT=/path/to/cert.pem TLS_KEY=/path/to/key.pem servedir
# or see -help

32
main.go
View File

@ -22,7 +22,8 @@ const postBody = `
</html>
`
var port = flag.Int("port", 8000, "port from which to serve")
var port = flag.Int("port", 8000, "port from which to serve http")
var tlsport = flag.Int("tlsport", 8443, "port from which to serve https")
var hidden = flag.Bool("hidden", false, "allow serving hidden dirs")
var canUpload = flag.Bool("upload", false, "enable upload interface")
@ -76,15 +77,38 @@ func main() {
if err != nil {
log.Fatal("problem getting hostname:", err)
}
log.Printf("serving on: http://%s:%d/", hostname, *port)
addr := fmt.Sprintf(":%d", *port)
tlsaddr := fmt.Sprintf(":%d", *tlsport)
http.Handle("/", logger(http.FileServer(http.Dir("./"))))
if *canUpload {
log.Printf("WARNING: uploading enabled")
http.HandleFunc("/upload/", upload)
}
if err := http.ListenAndServe(addr, nil); err != nil {
log.Fatal(err)
key := os.Getenv("TLS_KEY")
cert := os.Getenv("TLS_CERT")
url := fmt.Sprintf("http://%s:%d/", hostname, *tlsport)
if key != "" && cert != "" {
tlsUrl := fmt.Sprintf("https://%s:%d/", hostname, *tlsport)
go func() {
log.Printf("serving redirect on: %s", url)
sm := http.NewServeMux()
sm.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
http.Redirect(w, req, tlsUrl, http.StatusPermanentRedirect)
})
if err := http.ListenAndServe(addr, sm); err != nil {
log.Fatal(err)
}
}()
log.Printf("serving on: %s", tlsUrl)
if err := http.ListenAndServeTLS(tlsaddr, cert, key, nil); err != nil {
log.Fatal(err)
}
} else {
log.Printf("serving on: %s", url)
if err := http.ListenAndServe(addr, nil); err != nil {
log.Fatal(err)
}
}
}