Add explicit deadline for auth request

An explicit timeout is passed to the handler and a new unit test
proves that the functionality is in place. A additional return
statement was needed in the handler as pointed out by
@stefanprodan.

Signed-off-by: Alex Ellis <alexellis2@gmail.com>
This commit is contained in:
Alex Ellis
2019-06-05 13:08:55 +01:00
parent a66097a9f9
commit 35508ac70b
2 changed files with 59 additions and 16 deletions

View File

@ -1 +1,37 @@
package handlers
import (
"context"
"net/http"
"time"
)
// MakeExternalAuthHandler make an authentication proxy handler
func MakeExternalAuthHandler(next http.HandlerFunc, upstreamTimeout time.Duration, upstreamURL string, passBody bool) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
req, _ := http.NewRequest(http.MethodGet, upstreamURL, nil)
deadlineContext, cancel := context.WithDeadline(
context.Background(),
time.Now().Add(upstreamTimeout))
defer cancel()
res, err := http.DefaultClient.Do(req.WithContext(deadlineContext))
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
if res.Body != nil {
defer res.Body.Close()
}
if res.StatusCode == http.StatusOK {
next.ServeHTTP(w, r)
return
}
w.WriteHeader(res.StatusCode)
}
}