summaryrefslogtreecommitdiffstats
path: root/client/http.go
blob: 77a1911066a43d87ea64f3a0f518585764d7af28 (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
75
76
77
78
79
80
81
82
83
84
85
package client

import (
	"context"
	"crypto/tls"
	"net"
	"net/http"
	"time"

	"gitea.com/gitea/proto-go/ping/v1/pingv1connect"
	"gitea.com/gitea/proto-go/runner/v1/runnerv1connect"

	"github.com/bufbuild/connect-go"
	"golang.org/x/net/http2"
)

// New returns a new runner client.
func New(endpoint, secret string, opts ...Option) *HTTPClient {
	cfg := &config{}

	// Loop through each option
	for _, opt := range opts {
		// Call the option giving the instantiated
		opt.apply(cfg)
	}

	interceptor := connect.UnaryInterceptorFunc(func(next connect.UnaryFunc) connect.UnaryFunc {
		return func(ctx context.Context, req connect.AnyRequest) (connect.AnyResponse, error) {
			req.Header().Set("X-Runner-Token", secret)
			return next(ctx, req)
		}
	})

	cfg.opts = append(cfg.opts, connect.WithInterceptors(interceptor))

	if cfg.httpClient == nil {
		cfg.httpClient = &http.Client{
			Timeout: 1 * time.Minute,
			CheckRedirect: func(*http.Request, []*http.Request) error {
				return http.ErrUseLastResponse
			},
			Transport: &http2.Transport{
				AllowHTTP: true,
				DialTLS: func(netw, addr string, cfg *tls.Config) (net.Conn, error) {
					return net.Dial(netw, addr)
				},
			},
		}
	}

	if cfg.skipVerify {
		cfg.httpClient = &http.Client{
			CheckRedirect: func(*http.Request, []*http.Request) error {
				return http.ErrUseLastResponse
			},
			Transport: &http.Transport{
				Proxy: http.ProxyFromEnvironment,
				TLSClientConfig: &tls.Config{
					InsecureSkipVerify: true,
				},
			},
		}
	}

	return &HTTPClient{
		PingServiceClient: pingv1connect.NewPingServiceClient(
			cfg.httpClient,
			endpoint,
			cfg.opts...,
		),
		RunnerServiceClient: runnerv1connect.NewRunnerServiceClient(
			cfg.httpClient,
			endpoint,
			cfg.opts...,
		),
	}
}

var _ Client = (*HTTPClient)(nil)

// An HTTPClient manages communication with the runner API.
type HTTPClient struct {
	pingv1connect.PingServiceClient
	runnerv1connect.RunnerServiceClient
}