Skip to content

Instantly share code, notes, and snippets.

@AkashiSN
Created Jan 30, 2021
Embed
What would you like to do?
Simple SSL Static File Server in go
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