@@ -12,6 +12,9 @@ import (
1212type options struct {
1313 ListenAddress string
1414 Folder string
15+ Username string
16+ Password string
17+ Realm string
1518 Verbose bool
1619}
1720
@@ -21,14 +24,22 @@ func main() {
2124 flag .StringVar (& opts .ListenAddress , "listen" , "0.0.0.0:8000" , "Address:Port" )
2225 flag .StringVar (& opts .Folder , "path" , "." , "Folder" )
2326 flag .BoolVar (& opts .Verbose , "v" , false , "Verbose" )
27+ flag .StringVar (& opts .Username , "username" , "" , "Basic auth username" )
28+ flag .StringVar (& opts .Password , "password" , "" , "Basic auth password" )
29+ flag .StringVar (& opts .Realm , "realm" , "Please enter username and password" , "Realm" )
2430 flag .Parse ()
2531
2632 if flag .NArg () > 0 && opts .Folder == "." {
2733 opts .Folder = flag .Args ()[0 ]
2834 }
2935
3036 log .Printf ("Serving %s on http://%s/..." , opts .Folder , opts .ListenAddress )
31- fmt .Println (http .ListenAndServe (opts .ListenAddress , loglayer (http .FileServer (http .Dir (opts .Folder )))))
37+ layers := loglayer (http .FileServer (http .Dir (opts .Folder )))
38+ if opts .Username != "" || opts .Password != "" {
39+ layers = loglayer (basicauthlayer (http .FileServer (http .Dir (opts .Folder ))))
40+ }
41+
42+ fmt .Println (http .ListenAndServe (opts .ListenAddress , layers ))
3243}
3344
3445func loglayer (handler http.Handler ) http.Handler {
@@ -47,6 +58,19 @@ func loglayer(handler http.Handler) http.Handler {
4758 })
4859}
4960
61+ func basicauthlayer (handler http.Handler ) http.HandlerFunc {
62+ return http .HandlerFunc (func (w http.ResponseWriter , r * http.Request ) {
63+ user , pass , ok := r .BasicAuth ()
64+ if ! ok || user != opts .Username || pass != opts .Password {
65+ w .Header ().Set ("WWW-Authenticate" , fmt .Sprintf ("Basic realm=\" %s\" " , opts .Realm ))
66+ w .WriteHeader (401 )
67+ w .Write ([]byte ("Unauthorized.\n " ))
68+ return
69+ }
70+ handler .ServeHTTP (w , r )
71+ })
72+ }
73+
5074type loggingResponseWriter struct {
5175 http.ResponseWriter
5276 statusCode int
0 commit comments