Skip to content

Commit

Permalink
don't create http client for each request in forwardAuth middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
juliens committed Feb 3, 2020
1 parent 1b63c95 commit 349ce00
Showing 1 changed file with 14 additions and 17 deletions.
31 changes: 14 additions & 17 deletions pkg/middlewares/auth/forward.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@ package auth

import (
"context"
"crypto/tls"
"fmt"
"io/ioutil"
"net"
"net/http"
"strings"
"time"

"github.com/containous/traefik/v2/pkg/config/dynamic"
"github.com/containous/traefik/v2/pkg/log"
Expand All @@ -29,7 +29,7 @@ type forwardAuth struct {
authResponseHeaders []string
next http.Handler
name string
tlsConfig *tls.Config
client http.Client
trustForwardHeader bool
}

Expand All @@ -45,13 +45,23 @@ func NewForward(ctx context.Context, next http.Handler, config dynamic.ForwardAu
trustForwardHeader: config.TrustForwardHeader,
}

// Ensure our request client does not follow redirects
fa.client = http.Client{
CheckRedirect: func(r *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
Timeout: 30 * time.Second,
}

if config.TLS != nil {
tlsConfig, err := config.TLS.CreateTLSConfig()
if err != nil {
return nil, err
}

fa.tlsConfig = tlsConfig
tr := http.DefaultTransport.(*http.Transport).Clone()
tr.TLSClientConfig = tlsConfig
fa.client.Transport = tr
}

return fa, nil
Expand All @@ -64,19 +74,6 @@ func (fa *forwardAuth) GetTracingInformation() (string, ext.SpanKindEnum) {
func (fa *forwardAuth) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
logger := log.FromContext(middlewares.GetLoggerCtx(req.Context(), fa.name, forwardedTypeName))

// Ensure our request client does not follow redirects
httpClient := http.Client{
CheckRedirect: func(r *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}

if fa.tlsConfig != nil {
httpClient.Transport = &http.Transport{
TLSClientConfig: fa.tlsConfig,
}
}

forwardReq, err := http.NewRequest(http.MethodGet, fa.address, nil)
tracing.LogRequest(tracing.GetSpan(req), forwardReq)
if err != nil {
Expand All @@ -94,7 +91,7 @@ func (fa *forwardAuth) ServeHTTP(rw http.ResponseWriter, req *http.Request) {

writeHeader(req, forwardReq, fa.trustForwardHeader)

forwardResponse, forwardErr := httpClient.Do(forwardReq)
forwardResponse, forwardErr := fa.client.Do(forwardReq)
if forwardErr != nil {
logMessage := fmt.Sprintf("Error calling %s. Cause: %s", fa.address, forwardErr)
logger.Debug(logMessage)
Expand Down

0 comments on commit 349ce00

Please sign in to comment.