summaryrefslogtreecommitdiff
path: root/internal/engine/httpclient.go
blob: e491cf58f30289e274d5749b483b533587b904f1 (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
package engine

import (
	"context"
	"fmt"
	"net"
	"net/http"
	"time"

	"golang.org/x/net/proxy"
)

func HTTPClientViaSOCKS5(host string, port int, timeout time.Duration) (*http.Client, error) {
	if host == "" || port <= 0 {
		return nil, fmt.Errorf("invalid local socks5 endpoint")
	}

	addr := fmt.Sprintf("%s:%d", host, port)
	dialer, err := proxy.SOCKS5("tcp", addr, nil, proxy.Direct)
	if err != nil {
		return nil, err
	}

	contextDialer, ok := dialer.(proxy.ContextDialer)
	if !ok {
		return nil, fmt.Errorf("socks5 dialer does not implement context dialing")
	}

	transport := &http.Transport{
		DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
			return contextDialer.DialContext(ctx, network, address)
		},
		ForceAttemptHTTP2:     true,
		MaxIdleConns:          10,
		IdleConnTimeout:       30 * time.Second,
		TLSHandshakeTimeout:   timeout,
		ResponseHeaderTimeout: timeout,
		ExpectContinueTimeout: time.Second,
	}

	return &http.Client{
		Timeout:   timeout,
		Transport: transport,
	}, nil
}