Set default user agent in proxy client

Signed-off-by: Han Verstraete (OpenFaaS Ltd) <han@openfaas.com>
This commit is contained in:
Han Verstraete (OpenFaaS Ltd) 2024-08-06 13:50:16 +02:00 committed by Alex Ellis
parent 1379805240
commit 4e80b96d19

View File

@ -4,10 +4,13 @@
package types package types
import ( import (
"fmt"
"net" "net"
"net/http" "net/http"
"net/url" "net/url"
"time" "time"
"github.com/openfaas/faas/gateway/version"
) )
// NewHTTPClientReverseProxy proxies to an upstream host through the use of a http.Client // NewHTTPClientReverseProxy proxies to an upstream host through the use of a http.Client
@ -31,18 +34,20 @@ func NewHTTPClientReverseProxy(baseURL *url.URL, timeout time.Duration, maxIdleC
// https://github.com/minio/minio/pull/5860 // https://github.com/minio/minio/pull/5860
// Taken from http.DefaultTransport in Go 1.11 // Taken from http.DefaultTransport in Go 1.11
h.Client.Transport = &http.Transport{ h.Client.Transport = &proxyTransport{
Proxy: http.ProxyFromEnvironment, Transport: &http.Transport{
DialContext: (&net.Dialer{ Proxy: http.ProxyFromEnvironment,
Timeout: timeout, DialContext: (&net.Dialer{
KeepAlive: timeout, Timeout: timeout,
DualStack: true, KeepAlive: timeout,
}).DialContext, DualStack: true,
MaxIdleConns: maxIdleConns, }).DialContext,
MaxIdleConnsPerHost: maxIdleConnsPerHost, MaxIdleConns: maxIdleConns,
IdleConnTimeout: 90 * time.Second, MaxIdleConnsPerHost: maxIdleConnsPerHost,
TLSHandshakeTimeout: 10 * time.Second, IdleConnTimeout: 90 * time.Second,
ExpectContinueTimeout: 1 * time.Second, TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
},
} }
return &h return &h
@ -54,3 +59,19 @@ type HTTPClientReverseProxy struct {
Client *http.Client Client *http.Client
Timeout time.Duration Timeout time.Duration
} }
// proxyTransport is an http.RoundTripper for the reverse proxy client.
// It ensures default headers like the `User-Agent` are set on requests.
type proxyTransport struct {
// Transport is the underlying HTTP transport to use when making requests.
Transport http.RoundTripper
}
// RoundTrip implements the RoundTripper interface.
func (t *proxyTransport) RoundTrip(req *http.Request) (*http.Response, error) {
if _, ok := req.Header["User-Agent"]; !ok {
req.Header.Set("User-Agent", fmt.Sprintf("openfaas-ce-gateway/%s", version.BuildVersion()))
}
return t.Transport.RoundTrip(req)
}