summaryrefslogtreecommitdiffstats
path: root/client/go/util/http.go
blob: bb70c3ec6db80e2b0d69709f7c602748da8f295e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// Copyright Yahoo. 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 (
	"crypto/tls"
	"fmt"
	"net/http"
	"time"

	"github.com/vespa-engine/vespa/client/go/build"
)

// 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)
	UseCertificate(certificate []tls.Certificate)
}

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 { // Set wanted timeout
		c.client.Timeout = timeout
	}
	return c.client.Do(request)
}

func (c *defaultHttpClient) UseCertificate(certificates []tls.Certificate) {
	c.client.Transport = &http.Transport{TLSClientConfig: &tls.Config{
		Certificates: certificates,
	}}
}

func CreateClient(timeout time.Duration) HttpClient {
	return &defaultHttpClient{
		client: &http.Client{Timeout: timeout},
	}
}

func HttpDo(request *http.Request, timeout time.Duration, description string) (*http.Response, error) {
	if request.Header == nil {
		request.Header = make(http.Header)
	}
	request.Header.Set("User-Agent", fmt.Sprintf("Vespa CLI/%s", build.Version))
	response, err := ActiveHttpClient.Do(request, timeout)
	if err != nil {
		return nil, err
	}
	return response, nil
}