add support for serving TLS
This commit is contained in:
parent
5ba960613c
commit
c13c59650e
@ -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
|
||||
|
28
main.go
28
main.go
@ -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)
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user