Skip to content

Commit

Permalink
http: Timeout is handled inside http.Client instead of context.WithTi…
Browse files Browse the repository at this point in the history
…meout
  • Loading branch information
rbeuque74 committed Aug 23, 2018
1 parent 9e01ebf commit 731029a
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 5 deletions.
15 changes: 10 additions & 5 deletions plugins/http/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"encoding/json"
"fmt"
"io/ioutil"
"net"
"net/http"
"time"

Expand Down Expand Up @@ -57,9 +58,6 @@ func (res result) Error() error {

// Run is performing the checker protocol
func (c *HTTPChecker) Run(ctx context.Context) plugins.Result {
httpCtx, cancel := context.WithTimeout(ctx, c.cfg.Timeout)
defer cancel()

model := result{
Cfg: c.cfg,
Result: plugins.STATE_CRITICAL,
Expand All @@ -72,17 +70,24 @@ func (c *HTTPChecker) Run(ctx context.Context) plugins.Result {
err = fmt.Errorf(plugins.RenderError(c.cfg.templates.ErrNewHTTPRequest, model))
return plugins.ResultFromError(c, err, "")
}
req = req.WithContext(httpCtx)
req = req.WithContext(ctx)

model.Request = *req

duration := time.Now()
client := http.DefaultClient
client := &http.Client{}
if c.client != nil {
client = c.client
}
c.client.Timeout = c.cfg.Timeout
resp, err := client.Do(req)
if err != nil {
if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
model.Err = err
model.ElapsedTime = c.cfg.Timeout
err = fmt.Errorf(plugins.RenderError(c.cfg.templates.ErrTimeoutCritical, model))
return plugins.ResultFromError(c, err, "")
}
model.Err = err
err = fmt.Errorf(plugins.RenderError(c.cfg.templates.ErrRequest, model))
return plugins.ResultFromError(c, err, "")
Expand Down
16 changes: 16 additions & 0 deletions plugins/http/http_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,8 +97,24 @@ func TestHTTPServerFails(t *testing.T) {
assert.Contains(t, result.Message, "critical timeout: request took")
assert.Contains(t, result.Message, "instead of 50ms")

// timeout
cfg["timeout"] = 65
genChecker, err = NewHTTPChecker(cfg, nil)
assert.Nilf(t, err, "http checker instantiation failed: %q", err)

checker = genChecker.(*HTTPChecker)
checker.client = &httpclient

ctxRun, cancelFunc1 = context.WithTimeout(context.Background(), time.Second)
defer cancelFunc1()

result = checker.Run(ctxRun)
assert.Equal(t, plugins.STATE_CRITICAL, result.Status)
assert.Contains(t, result.Message, "critical timeout: request took 65ms instead of 50ms")

// bad status code
cfg["code"] = 400
cfg["timeout"] = 1000
genChecker, err = NewHTTPChecker(cfg, nil)
assert.Nilf(t, err, "http checker instantiation failed: %q", err)

Expand Down

0 comments on commit 731029a

Please sign in to comment.