Skip to content

Commit 0fcf82d

Browse files
committed
Add basic auth
1 parent dbeae85 commit 0fcf82d

File tree

3 files changed

+27
-6
lines changed

3 files changed

+27
-6
lines changed

src/argparse.go

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,12 +19,13 @@ var (
1919
)
2020

2121
var CLI struct {
22-
Port int `help:"port where to serve" short:p default:9999`
23-
ResponseDelay []int `help:"server response delay in ms, use twice to define range for a random value before each request" short:r`
24-
JSONLog bool `help:"enable json log, instead of text one" short:j`
25-
LogFile string `help:"log file" short:l default:/dev/stdout`
26-
Verbose bool `help:"verbose mode, print full response data set" short:v`
27-
VersionFlag bool `help:"display version" short:V`
22+
Port int `help:"port where to serve" short:p default:9999`
23+
BasicAuth []string `help:"enable basic auth" short:b placeholder:USER:PASS sep::`
24+
ResponseDelay []int `help:"server response delay in ms, use twice to define range for a random value before each request" short:r`
25+
JSONLog bool `help:"enable json log, instead of text one" short:j`
26+
LogFile string `help:"log file" short:l default:/dev/stdout`
27+
Verbose bool `help:"verbose mode, print full response data set" short:v`
28+
VersionFlag bool `help:"display version" short:V`
2829
}
2930

3031
func parseArgs() {

src/main.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ type tConf struct {
1717
Bind string
1818
Port int
1919
ResponseDelay []int
20+
BasicAuth []string
2021
}
2122

2223
func main() {
@@ -25,6 +26,7 @@ func main() {
2526
conf := tConf{
2627
Port: CLI.Port,
2728
ResponseDelay: CLI.ResponseDelay,
29+
BasicAuth: CLI.BasicAuth,
2830
}
2931

3032
lg = logging.Init(CLI.LogFile, CLI.JSONLog)

src/server.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,24 @@ func (h *handler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
4141
) * time.Millisecond,
4242
)
4343
}
44+
45+
if len(CLI.BasicAuth) > 0 {
46+
user, pass, ok := req.BasicAuth()
47+
if !ok {
48+
fmt.Println("Error parsing basic auth")
49+
resp.WriteHeader(401)
50+
return
51+
}
52+
if user != CLI.BasicAuth[0] || pass != CLI.BasicAuth[1] {
53+
lg.LogError("Credentials incorrect", logrus.Fields{
54+
"user": user,
55+
"pass": pass,
56+
})
57+
resp.WriteHeader(401)
58+
return
59+
}
60+
}
61+
4462
responseCode := parseResponseCode(req.URL.String())
4563
resp.WriteHeader(responseCode)
4664
data := tResponse{

0 commit comments

Comments
 (0)