summaryrefslogtreecommitdiff
path: root/go/internal/config/httpclient.go
diff options
context:
space:
mode:
authorIgor Drozdov <idrozdov@gitlab.com>2019-04-23 14:07:38 +0300
committerIgor Drozdov <idrozdov@gitlab.com>2019-04-23 14:23:31 +0300
commitfbaba66e124441d0e283fd4e2966d7af790ce23a (patch)
treeb7560b534f9290b4f9b341f956c22d10d7db95dc /go/internal/config/httpclient.go
parent9ed567b6fd14ef389df11b46be3022a90eda68ec (diff)
downloadgitlab-shell-id-api-regular-http.tar.gz
Move http client building to configid-api-regular-http
Diffstat (limited to 'go/internal/config/httpclient.go')
-rw-r--r--go/internal/config/httpclient.go74
1 files changed, 74 insertions, 0 deletions
diff --git a/go/internal/config/httpclient.go b/go/internal/config/httpclient.go
new file mode 100644
index 0000000..82807a6
--- /dev/null
+++ b/go/internal/config/httpclient.go
@@ -0,0 +1,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
+}