2020-07-04 18:41:58 +01:00
|
|
|
package middleware
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
|
2021-03-21 11:20:57 -07:00
|
|
|
"github.com/google/uuid"
|
2020-07-04 18:41:58 +01:00
|
|
|
"github.com/justinas/alice"
|
2020-09-30 01:44:42 +09:00
|
|
|
middlewareapi "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware"
|
2020-07-04 18:41:58 +01:00
|
|
|
)
|
|
|
|
|
2021-03-21 11:20:57 -07:00
|
|
|
func NewScope(reverseProxy bool, idHeader string) alice.Constructor {
|
2020-12-23 17:42:02 -08:00
|
|
|
return func(next http.Handler) http.Handler {
|
|
|
|
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
|
|
|
|
scope := &middlewareapi.RequestScope{
|
2021-01-02 13:16:01 -08:00
|
|
|
ReverseProxy: reverseProxy,
|
2021-03-21 11:20:57 -07:00
|
|
|
RequestID: genRequestID(req, idHeader),
|
2020-12-23 17:42:02 -08:00
|
|
|
}
|
2021-01-02 13:16:01 -08:00
|
|
|
req = middlewareapi.AddRequestScope(req, scope)
|
|
|
|
next.ServeHTTP(rw, req)
|
2020-12-23 17:42:02 -08:00
|
|
|
})
|
|
|
|
}
|
2020-07-04 18:41:58 +01:00
|
|
|
}
|
2021-03-21 11:20:57 -07:00
|
|
|
|
|
|
|
// genRequestID sets a request-wide ID for use in logging or error pages.
|
|
|
|
// If a RequestID header is set, it uses that. Otherwise, it generates a random
|
|
|
|
// UUID for the lifespan of the request.
|
|
|
|
func genRequestID(req *http.Request, idHeader string) string {
|
|
|
|
rid := req.Header.Get(idHeader)
|
|
|
|
if rid != "" {
|
|
|
|
return rid
|
|
|
|
}
|
|
|
|
return uuid.New().String()
|
|
|
|
}
|