Browse Source

add support for serving TLS

Stephen McQuay 2 years ago
parent
commit
c13c59650e
No known key found for this signature in database
2 changed files with 31 additions and 4 deletions
  1. 3
    0
      README.md
  2. 28
    4
      main.go

+ 3
- 0
README.md View File

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

+ 28
- 4
main.go View File

@@ -22,7 +22,8 @@ const postBody = `
22 22
 </html>
23 23
 `
24 24
 
25
-var port = flag.Int("port", 8000, "port from which to serve")
25
+var port = flag.Int("port", 8000, "port from which to serve http")
26
+var tlsport = flag.Int("tlsport", 8443, "port from which to serve https")
26 27
 var hidden = flag.Bool("hidden", false, "allow serving hidden dirs")
27 28
 var canUpload = flag.Bool("upload", false, "enable upload interface")
28 29
 
@@ -76,15 +77,38 @@ func main() {
76 77
 	if err != nil {
77 78
 		log.Fatal("problem getting hostname:", err)
78 79
 	}
79
-	log.Printf("serving on: http://%s:%d/", hostname, *port)
80 80
 	addr := fmt.Sprintf(":%d", *port)
81
+	tlsaddr := fmt.Sprintf(":%d", *tlsport)
81 82
 
82 83
 	http.Handle("/", logger(http.FileServer(http.Dir("./"))))
83 84
 	if *canUpload {
84 85
 		log.Printf("WARNING: uploading enabled")
85 86
 		http.HandleFunc("/upload/", upload)
86 87
 	}
87
-	if err := http.ListenAndServe(addr, nil); err != nil {
88
-		log.Fatal(err)
88
+
89
+	key := os.Getenv("TLS_KEY")
90
+	cert := os.Getenv("TLS_CERT")
91
+	url := fmt.Sprintf("http://%s:%d/", hostname, *tlsport)
92
+	if key != "" && cert != "" {
93
+		tlsUrl := fmt.Sprintf("https://%s:%d/", hostname, *tlsport)
94
+		go func() {
95
+			log.Printf("serving redirect on: %s", url)
96
+			sm := http.NewServeMux()
97
+			sm.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
98
+				http.Redirect(w, req, tlsUrl, http.StatusPermanentRedirect)
99
+			})
100
+			if err := http.ListenAndServe(addr, sm); err != nil {
101
+				log.Fatal(err)
102
+			}
103
+		}()
104
+		log.Printf("serving on: %s", tlsUrl)
105
+		if err := http.ListenAndServeTLS(tlsaddr, cert, key, nil); err != nil {
106
+			log.Fatal(err)
107
+		}
108
+	} else {
109
+		log.Printf("serving on: %s", url)
110
+		if err := http.ListenAndServe(addr, nil); err != nil {
111
+			log.Fatal(err)
112
+		}
89 113
 	}
90 114
 }

Loading…
Cancel
Save