Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Set default user agent in proxy client #1843

Merged
merged 1 commit into from
Aug 7, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 33 additions & 12 deletions gateway/types/proxy_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,13 @@
package types

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

"github.com/openfaas/faas/gateway/version"
)

// NewHTTPClientReverseProxy proxies to an upstream host through the use of a http.Client
Expand All @@ -31,18 +34,20 @@ func NewHTTPClientReverseProxy(baseURL *url.URL, timeout time.Duration, maxIdleC
// https://github.com/minio/minio/pull/5860

// Taken from http.DefaultTransport in Go 1.11
h.Client.Transport = &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: timeout,
KeepAlive: timeout,
DualStack: true,
}).DialContext,
MaxIdleConns: maxIdleConns,
MaxIdleConnsPerHost: maxIdleConnsPerHost,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
h.Client.Transport = &proxyTransport{
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: timeout,
KeepAlive: timeout,
DualStack: true,
}).DialContext,
MaxIdleConns: maxIdleConns,
MaxIdleConnsPerHost: maxIdleConnsPerHost,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
},
}

return &h
Expand All @@ -54,3 +59,19 @@ type HTTPClientReverseProxy struct {
Client *http.Client
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)
}