@@ -12,6 +12,9 @@ import (
12
12
type options struct {
13
13
ListenAddress string
14
14
Folder string
15
+ Username string
16
+ Password string
17
+ Realm string
15
18
Verbose bool
16
19
}
17
20
@@ -21,14 +24,22 @@ func main() {
21
24
flag .StringVar (& opts .ListenAddress , "listen" , "0.0.0.0:8000" , "Address:Port" )
22
25
flag .StringVar (& opts .Folder , "path" , "." , "Folder" )
23
26
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" )
24
30
flag .Parse ()
25
31
26
32
if flag .NArg () > 0 && opts .Folder == "." {
27
33
opts .Folder = flag .Args ()[0 ]
28
34
}
29
35
30
36
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 ))
32
43
}
33
44
34
45
func loglayer (handler http.Handler ) http.Handler {
@@ -47,6 +58,19 @@ func loglayer(handler http.Handler) http.Handler {
47
58
})
48
59
}
49
60
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
+
50
74
type loggingResponseWriter struct {
51
75
http.ResponseWriter
52
76
statusCode int
0 commit comments