Skip to content

Commit

Permalink
Merge pull request #249 from nonylene/check-http-max-redirects
Browse files Browse the repository at this point in the history
[check-http] Add --max-redirects option
  • Loading branch information
susisu committed Sep 7, 2018
2 parents f157128 + 344ca83 commit ac5388f
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
7 changes: 7 additions & 0 deletions check-http/lib/check_http.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ type checkHTTPOpts struct {
SourceIP string `short:"i" long:"source-ip" description:"source IP address"`
Headers []string `short:"H" description:"HTTP request headers"`
Regexp string `short:"p" long:"pattern" description:"Expected pattern in the content"`
MaxRedirects int `long:"max-redirects" description:"Maximum number of redirects followed" default:"10"`
}

// Do the plugin
Expand Down Expand Up @@ -138,6 +139,12 @@ func Run(args []string) *checkers.Checker {
}).Dial
}
client := &http.Client{Transport: tr}
client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
if len(via) > opts.MaxRedirects {
return http.ErrUseLastResponse
}
return nil
}

req, err := http.NewRequest("GET", opts.URL, nil)
if err != nil {
Expand Down
36 changes: 36 additions & 0 deletions check-http/lib/check_http_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,3 +133,39 @@ func TestExpectedContent(t *testing.T) {
assert.Equal(t, ckr.Status, tc.status, "#%d: Status should be %s", i, tc.status)
}
}

func TestMaxRedirects(t *testing.T) {
redirectedPath := "/redirected"
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != redirectedPath {
http.Redirect(w, r, redirectedPath, 301)
}
}))
defer ts.Close()

testCases := []struct {
args []string
want checkers.Status
}{
{
args: []string{"-s", "301=ok", "-s", "100-300=warning", "-s", "302-599=warning",
"-u", ts.URL, "--max-redirects", "0"},
want: checkers.OK,
},
{
args: []string{"-s", "200=ok", "-s", "100-199=warning", "-s", "201-599=warning",
"-u", ts.URL, "--max-redirects", "1"},
want: checkers.OK,
},
{
args: []string{"-s", "200=ok", "-s", "100-199=warning", "-s", "201-599=warning",
"-u", ts.URL},
want: checkers.OK,
},
}

for i, tc := range testCases {
ckr := Run(tc.args)
assert.Equal(t, ckr.Status, tc.want, "#%d: Status should be %s", i, tc.want)
}
}

0 comments on commit ac5388f

Please sign in to comment.