diff options
author | Jon Bratseth <bratseth@oath.com> | 2021-08-24 19:51:59 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-08-24 19:51:59 +0200 |
commit | fe557fc926fd40305d9f04f9fd749d39cfbc4ea1 (patch) | |
tree | 8bebe5ab2416c4cc52741eca6dab24e895373734 /client/go/util/http.go | |
parent | 8fe4a6cd8ad9b13d7ac0352854533a641871e2ed (diff) | |
parent | c292201c97b583448212442725e56499ed30b100 (diff) |
Merge pull request #18836 from vespa-engine/bratseth/cli-3
Bratseth/cli 3
Diffstat (limited to 'client/go/util/http.go')
-rw-r--r-- | client/go/util/http.go | 55 |
1 files changed, 55 insertions, 0 deletions
diff --git a/client/go/util/http.go b/client/go/util/http.go new file mode 100644 index 00000000000..24e2416117c --- /dev/null +++ b/client/go/util/http.go @@ -0,0 +1,55 @@ +// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. +// A HTTP wrapper which handles some errors and provides a way to replace the HTTP client by a mock. +// Author: bratseth + +package util + +import ( + "net/http" + "net/url" + "strings" + "time" +) + +// Set this to a mock HttpClient instead to unit test HTTP requests +var ActiveHttpClient = CreateClient(time.Second * 10) + +type HttpClient interface { + Do(request *http.Request, timeout time.Duration) (response *http.Response, error error) +} + +type defaultHttpClient struct { + client *http.Client +} + +func (c *defaultHttpClient) Do(request *http.Request, timeout time.Duration) (response *http.Response, error error) { + if c.client.Timeout != timeout { // Create a new client with the right timeout + c.client = &http.Client{Timeout: timeout,} + } + return c.client.Do(request) +} + +func CreateClient(timeout time.Duration) HttpClient { + return &defaultHttpClient{ + client: &http.Client{Timeout: timeout,}, + } +} + +// Convenience function for doing a HTTP GET +func HttpGet(host string, path string, description string) *http.Response { + url, urlError := url.Parse(host + path) + if urlError != nil { + Error("Invalid target url '" + host + path + "'") + return nil + } + return HttpDo(&http.Request{URL: url,}, time.Second * 10, description) +} + +func HttpDo(request *http.Request, timeout time.Duration, description string) *http.Response { + response, error := ActiveHttpClient.Do(request, timeout) + if error != nil { + Error("Could not connect to", strings.ToLower(description), "at", request.URL.Host) + Detail(error.Error()) + } + return response +} |