Skip to content

Commit 526bfd9

Browse files
committed
refactoring basic auth option
1 parent 71c06d3 commit 526bfd9

File tree

1 file changed

+14
-6
lines changed

1 file changed

+14
-6
lines changed

simplehttpserver.go

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,15 @@ import (
99
"net/http"
1010
"net/http/httputil"
1111
"path"
12+
"strings"
1213
)
1314

1415
type options struct {
1516
ListenAddress string
1617
Folder string
17-
Username string
18-
Password string
18+
BasicAuth string
19+
username string
20+
password string
1921
Realm string
2022
Certificate string
2123
Key string
@@ -34,8 +36,7 @@ func main() {
3436
flag.StringVar(&opts.Certificate, "cert", "", "Certificate")
3537
flag.StringVar(&opts.Key, "key", "", "Key")
3638
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.BasicAuth, "basic-auth", "", "Basic auth (username:password)")
3940
flag.StringVar(&opts.Realm, "realm", "Please enter username and password", "Realm")
4041

4142
flag.Parse()
@@ -46,7 +47,14 @@ func main() {
4647

4748
log.Printf("Serving %s on http://%s/...", opts.Folder, opts.ListenAddress)
4849
layers := loglayer(http.FileServer(http.Dir(opts.Folder)))
49-
if opts.Username != "" || opts.Password != "" {
50+
if opts.BasicAuth != "" {
51+
baTokens := strings.SplitN(opts.BasicAuth, ":", 1)
52+
if len(baTokens) > 0 {
53+
opts.username = baTokens[0]
54+
}
55+
if len(baTokens) > 1 {
56+
opts.password = baTokens[1]
57+
}
5058
layers = loglayer(basicauthlayer(http.FileServer(http.Dir(opts.Folder))))
5159
}
5260

@@ -94,7 +102,7 @@ func loglayer(handler http.Handler) http.Handler {
94102
func basicauthlayer(handler http.Handler) http.HandlerFunc {
95103
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
96104
user, pass, ok := r.BasicAuth()
97-
if !ok || user != opts.Username || pass != opts.Password {
105+
if !ok || user != opts.username || pass != opts.password {
98106
w.Header().Set("WWW-Authenticate", fmt.Sprintf("Basic realm=\"%s\"", opts.Realm))
99107
w.WriteHeader(http.StatusUnauthorized)
100108
w.Write([]byte("Unauthorized.\n")) //nolint

0 commit comments

Comments
 (0)