Passed
Pull Request — master (#41)
by Stefano
02:42
created

pkg/scan/client/client.go   A

Size/Duplication

Total Lines 78
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
cc 12
eloc 52
dl 0
loc 78
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
D client.NewClientFromConfig 0 63 12
1
package client
2
3
import (
4
	"context"
5
	"net"
6
	"net/http"
7
	"net/http/cookiejar"
8
	"net/url"
9
	"time"
10
11
	"github.com/pkg/errors"
12
	"github.com/stefanoj3/dirstalk/pkg/scan/client/cookie"
13
	"golang.org/x/net/proxy"
14
)
15
16
func NewClientFromConfig(
0 ignored issues
show
introduced by
exported function NewClientFromConfig should have comment or be unexported
Loading history...
17
	timeoutInMilliseconds int,
18
	socks5Url *url.URL,
19
	userAgent string,
20
	useCookieJar bool,
21
	cookies []*http.Cookie,
22
	headers map[string]string,
23
	u *url.URL,
24
) (*http.Client, error) {
25
	transport := http.Transport{
26
		MaxIdleConns:          100,
27
		IdleConnTimeout:       90 * time.Second,
28
		TLSHandshakeTimeout:   10 * time.Second,
29
		ExpectContinueTimeout: 1 * time.Second,
30
	}
31
32
	c := &http.Client{
33
		Timeout:   time.Millisecond * time.Duration(timeoutInMilliseconds),
34
		Transport: &transport,
35
	}
36
37
	if useCookieJar {
38
		jar, err := cookiejar.New(nil)
39
		if err != nil {
40
			return nil, errors.Wrap(err, "NewClientFromConfig: failed to create cookie jar")
41
		}
42
		c.Jar = jar
43
	}
44
45
	if c.Jar != nil {
46
		c.Jar.SetCookies(u, cookies)
47
	}
48
49
	if len(cookies) > 0 && c.Jar == nil {
50
		c.Jar = cookie.NewStatelessJar(cookies)
51
	}
52
53
	if socks5Url != nil {
54
		tbDialer, err := proxy.FromURL(socks5Url, proxy.Direct)
55
		if err != nil {
56
			return nil, errors.Wrap(err, "NewClientFromConfig: failed to create socks5 proxy")
57
		}
58
59
		transport.DialContext = func(ctx context.Context, network, addr string) (conn net.Conn, e error) {
60
			return tbDialer.Dial(network, addr)
61
		}
62
	}
63
64
	var err error
65
66
	c.Transport, err = decorateTransportWithUserAgentDecorator(c.Transport, userAgent)
67
	if err != nil {
68
		return nil, errors.Wrap(err, "NewClientFromConfig: failed to decorate transport")
69
	}
70
71
	if len(headers) > 0 {
72
		c.Transport, err = decorateTransportWithHeadersDecorator(c.Transport, headers)
73
		if err != nil {
74
			return nil, errors.Wrap(err, "NewClientFromConfig: failed to decorate transport")
75
		}
76
	}
77
78
	return c, nil
79
}
80