-
Notifications
You must be signed in to change notification settings - Fork 301
/
http.go
142 lines (122 loc) · 4.23 KB
/
http.go
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
// Copyright © 2021 The Things Network Foundation, The Things Industries B.V.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package httpclient
import (
"context"
"crypto/tls"
"fmt"
"net/http"
"runtime"
"time"
"github.com/gregjones/httpcache"
"github.com/klauspost/compress/gzhttp"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
"go.opentelemetry.io/otel/metric/noop"
"go.thethings.network/lorawan-stack/v3/pkg/config/tlsconfig"
"go.thethings.network/lorawan-stack/v3/pkg/telemetry/tracing"
"go.thethings.network/lorawan-stack/v3/pkg/version"
)
// defaultHTTPClientTimeout is the default timeout for the HTTP client.
const defaultHTTPClientTimeout = 10 * time.Second
// TLSClientConfigurationProvider provides a *tls.Config to be used by TLS clients.
type TLSClientConfigurationProvider interface {
GetTLSClientConfig(context.Context, ...tlsconfig.Option) (*tls.Config, error)
}
// Provider constructs *http.Clients.
type Provider interface {
HTTPClient(context.Context, ...Option) (*http.Client, error)
}
// Option is an option for HTTP clients.
type Option func(*httpClientOptions)
type httpClientOptions struct {
cache bool
tlsConfig *tls.Config
tlsConfigOptions []tlsconfig.Option
}
// WithCache enables caching at transport level.
func WithCache(b bool) Option {
return Option(func(o *httpClientOptions) {
o.cache = true
})
}
// WithTLSConfig configures the TLS configuration to be used by the transport.
func WithTLSConfig(c *tls.Config) Option {
return Option(func(o *httpClientOptions) {
o.tlsConfig = c
})
}
// WithTLSConfigOptions configures the TLS configuration options provided to the TLS configuration provider
// by the transport.
func WithTLSConfigOptions(opts ...tlsconfig.Option) Option {
return Option(func(o *httpClientOptions) {
o.tlsConfigOptions = opts
})
}
type provider struct {
tlsConfigProvider TLSClientConfigurationProvider
}
// HTTPClient returns a new *http.Client with a default timeout and a configured transport.
func (p *provider) HTTPClient(ctx context.Context, opts ...Option) (*http.Client, error) {
options := &httpClientOptions{}
for _, opt := range opts {
opt(options)
}
if options.tlsConfig == nil {
tlsConfig, err := p.tlsConfigProvider.GetTLSClientConfig(ctx, options.tlsConfigOptions...)
if err != nil {
return nil, err
}
options.tlsConfig = tlsConfig
}
transport := http.DefaultTransport.(*http.Transport).Clone()
transport.TLSClientConfig = options.tlsConfig
var rt http.RoundTripper = transport
rt = gzhttp.Transport(rt)
rt = otelhttp.NewTransport(
rt,
otelhttp.WithTracerProvider(tracing.FromContext(ctx)),
// As pkg/metrics is currently Prometheus based, the OpenTelemetry metrics are unused.
// TODO: https://github.com/TheThingsNetwork/lorawan-stack/issues/5692.
otelhttp.WithMeterProvider(noop.MeterProvider{}),
)
if options.cache {
rt = &httpcache.Transport{
Transport: rt,
Cache: httpcache.NewMemoryCache(),
MarkCachedResponses: true,
}
}
rt = &roundTripperWithUserAgent{
RoundTripper: rt,
UserAgent: fmt.Sprintf("TheThingsStack/%s (%s/%s)", version.TTN, runtime.GOOS, runtime.GOARCH),
}
return &http.Client{
Timeout: defaultHTTPClientTimeout,
Transport: rt,
}, nil
}
// NewProvider constructs a Provider on top of the provided TLS configuration provider.
func NewProvider(tlsConfigProvider TLSClientConfigurationProvider) Provider {
return &provider{tlsConfigProvider: tlsConfigProvider}
}
type roundTripperWithUserAgent struct {
http.RoundTripper
UserAgent string
}
func (rt *roundTripperWithUserAgent) RoundTrip(r *http.Request) (*http.Response, error) {
if r.Header.Get("User-Agent") == "" {
r.Header.Set("User-Agent", rt.UserAgent)
}
return rt.RoundTripper.RoundTrip(r)
}