Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 26 additions & 2 deletions simplehttpserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ import (
type options struct {
ListenAddress string
Folder string
Username string
Password string
Realm string
Certificate string
Key string
HTTPS bool
Expand All @@ -31,6 +34,9 @@ func main() {
flag.StringVar(&opts.Certificate, "cert", "", "Certificate")
flag.StringVar(&opts.Key, "key", "", "Key")
flag.BoolVar(&opts.Verbose, "v", false, "Verbose")
flag.StringVar(&opts.Username, "username", "", "Basic auth username")
flag.StringVar(&opts.Password, "password", "", "Basic auth password")
flag.StringVar(&opts.Realm, "realm", "Please enter username and password", "Realm")

flag.Parse()

Expand All @@ -39,16 +45,21 @@ func main() {
}

log.Printf("Serving %s on http://%s/...", opts.Folder, opts.ListenAddress)
layers := loglayer(http.FileServer(http.Dir(opts.Folder)))
if opts.Username != "" || opts.Password != "" {
layers = loglayer(basicauthlayer(http.FileServer(http.Dir(opts.Folder))))
}

if opts.Upload {
log.Println("Upload enabled")
}
if opts.HTTPS {
if opts.Certificate == "" || opts.Key == "" {
log.Fatal("Certificate or Key file not specified")
}
fmt.Println(http.ListenAndServeTLS(opts.ListenAddress, opts.Certificate, opts.Key, loglayer(http.FileServer(http.Dir(opts.Folder)))))
fmt.Println(http.ListenAndServeTLS(opts.ListenAddress, opts.Certificate, opts.Key, layers))
} else {
fmt.Println(http.ListenAndServe(opts.ListenAddress, loglayer(http.FileServer(http.Dir(opts.Folder)))))
fmt.Println(http.ListenAndServe(opts.ListenAddress, layers))
}
}

Expand Down Expand Up @@ -80,6 +91,19 @@ func loglayer(handler http.Handler) http.Handler {
})
}

func basicauthlayer(handler http.Handler) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user, pass, ok := r.BasicAuth()
if !ok || user != opts.Username || pass != opts.Password {
w.Header().Set("WWW-Authenticate", fmt.Sprintf("Basic realm=\"%s\"", opts.Realm))
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte("Unauthorized.\n")) //nolint
return
}
handler.ServeHTTP(w, r)
})
}

type loggingResponseWriter struct {
http.ResponseWriter
statusCode int
Expand Down