Created
January 30, 2021 12:55
-
-
Save AkashiSN/335746cab435676399b0ce37dd93907b to your computer and use it in GitHub Desktop.
Simple SSL Static File Server in go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"crypto/tls" | |
"flag" | |
"log" | |
"net/http" | |
"time" | |
) | |
func logger(h http.Handler) http.Handler { | |
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
rAddr := r.RemoteAddr | |
method := r.Method | |
path := r.URL.Path | |
log.Printf("Remote: %s [%s] %s\n", rAddr, method, path) | |
h.ServeHTTP(w, r) | |
}) | |
} | |
func main() { | |
port := flag.String("p", "8443", "port to serve on") | |
directory := flag.String("d", ".", "the directory of static file to host") | |
cert := flag.String("c", "", "path to cert file") | |
privKey := flag.String("k", "", "path to private key file") | |
flag.Parse() | |
muxSSL := http.NewServeMux() | |
muxSSL.HandleFunc("/", logger(http.FileServer(http.Dir(*directory))).ServeHTTP) | |
tlsConfig := &tls.Config{} | |
tlsConfig.Certificates = make([]tls.Certificate, 1) | |
var err error | |
tlsConfig.Certificates[0], err = tls.LoadX509KeyPair(*cert, *privKey) | |
if err != nil { | |
log.Fatal(err) | |
} | |
tlsConfig.BuildNameToCertificate() | |
ServerSSL := &http.Server{ | |
Handler: muxSSL, | |
ReadTimeout: 10 * time.Second, | |
WriteTimeout: 10 * time.Second, | |
MaxHeaderBytes: 1 << 20, | |
} | |
listener, err := tls.Listen("tcp", ":"+*port, tlsConfig) | |
if err != nil { | |
log.Fatal(err) | |
} | |
log.Printf("Serving %s on HTTPS port: :%s\n", *directory, *port) | |
err = ServerSSL.Serve(listener) | |
if err != nil { | |
log.Fatal(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment