@@ -14,6 +14,9 @@ import (
1414type options struct {
1515 ListenAddress string
1616 Folder string
17+ Username string
18+ Password string
19+ Realm string
1720 Certificate string
1821 Key string
1922 HTTPS bool
@@ -31,6 +34,9 @@ func main() {
3134 flag .StringVar (& opts .Certificate , "cert" , "" , "Certificate" )
3235 flag .StringVar (& opts .Key , "key" , "" , "Key" )
3336 flag .BoolVar (& opts .Verbose , "v" , false , "Verbose" )
37+ flag .StringVar (& opts .Username , "username" , "" , "Basic auth username" )
38+ flag .StringVar (& opts .Password , "password" , "" , "Basic auth password" )
39+ flag .StringVar (& opts .Realm , "realm" , "Please enter username and password" , "Realm" )
3440
3541 flag .Parse ()
3642
@@ -39,16 +45,21 @@ func main() {
3945 }
4046
4147 log .Printf ("Serving %s on http://%s/..." , opts .Folder , opts .ListenAddress )
48+ layers := loglayer (http .FileServer (http .Dir (opts .Folder )))
49+ if opts .Username != "" || opts .Password != "" {
50+ layers = loglayer (basicauthlayer (http .FileServer (http .Dir (opts .Folder ))))
51+ }
52+
4253 if opts .Upload {
4354 log .Println ("Upload enabled" )
4455 }
4556 if opts .HTTPS {
4657 if opts .Certificate == "" || opts .Key == "" {
4758 log .Fatal ("Certificate or Key file not specified" )
4859 }
49- fmt .Println (http .ListenAndServeTLS (opts .ListenAddress , opts .Certificate , opts .Key , loglayer ( http . FileServer ( http . Dir ( opts . Folder ))) ))
60+ fmt .Println (http .ListenAndServeTLS (opts .ListenAddress , opts .Certificate , opts .Key , layers ))
5061 } else {
51- fmt .Println (http .ListenAndServe (opts .ListenAddress , loglayer ( http . FileServer ( http . Dir ( opts . Folder ))) ))
62+ fmt .Println (http .ListenAndServe (opts .ListenAddress , layers ))
5263 }
5364}
5465
@@ -80,6 +91,19 @@ func loglayer(handler http.Handler) http.Handler {
8091 })
8192}
8293
94+ func basicauthlayer (handler http.Handler ) http.HandlerFunc {
95+ return http .HandlerFunc (func (w http.ResponseWriter , r * http.Request ) {
96+ user , pass , ok := r .BasicAuth ()
97+ if ! ok || user != opts .Username || pass != opts .Password {
98+ w .Header ().Set ("WWW-Authenticate" , fmt .Sprintf ("Basic realm=\" %s\" " , opts .Realm ))
99+ w .WriteHeader (http .StatusUnauthorized )
100+ w .Write ([]byte ("Unauthorized.\n " )) //nolint
101+ return
102+ }
103+ handler .ServeHTTP (w , r )
104+ })
105+ }
106+
83107type loggingResponseWriter struct {
84108 http.ResponseWriter
85109 statusCode int
0 commit comments