summaryrefslogtreecommitdiff
path: root/go/internal/config/httpclient.go
blob: 82807a62b2c1ca6b72e7ae21313ee517e7fa3747 (plain)
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package config

import (
	"context"
	"net"
	"net/http"
	"strings"
	"time"
)

const (
	socketBaseUrl             = "http://unix"
	UnixSocketProtocol        = "http+unix://"
	HttpProtocol              = "http://"
	defaultReadTimeoutSeconds = 300
)

type HttpClient struct {
	HttpClient *http.Client
	Host       string
}

func (c *Config) GetHttpClient() *HttpClient {
	if c.HttpClient != nil {
		return c.HttpClient
	}

	var transport *http.Transport
	var host string
	if strings.HasPrefix(c.GitlabUrl, UnixSocketProtocol) {
		transport, host = c.buildSocketTransport()
	} else if strings.HasPrefix(c.GitlabUrl, HttpProtocol) {
		transport, host = c.buildHttpTransport()
	} else {
		return nil
	}

	httpClient := &http.Client{
		Transport: transport,
		Timeout:   c.readTimeout(),
	}

	client := &HttpClient{HttpClient: httpClient, Host: host}

	c.HttpClient = client

	return client
}

func (c *Config) buildSocketTransport() (*http.Transport, string) {
	socketPath := strings.TrimPrefix(c.GitlabUrl, UnixSocketProtocol)
	transport := &http.Transport{
		DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
			dialer := net.Dialer{}
			return dialer.DialContext(ctx, "unix", socketPath)
		},
	}

	return transport, socketBaseUrl
}

func (c *Config) buildHttpTransport() (*http.Transport, string) {
	return &http.Transport{}, c.GitlabUrl
}

func (c *Config) readTimeout() time.Duration {
	timeoutSeconds := c.HttpSettings.ReadTimeoutSeconds

	if timeoutSeconds == 0 {
		timeoutSeconds = defaultReadTimeoutSeconds
	}

	return time.Duration(timeoutSeconds) * time.Second
}