Skip to content

Commit 608fd80

Browse files
committed
Provide access to admission.Request in custom validator/defaulter
1 parent 365ae09 commit 608fd80

File tree

3 files changed

+22
-1
lines changed

3 files changed

+22
-1
lines changed

pkg/webhook/admission/defaulter_custom.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@ package admission
1919
import (
2020
"context"
2121
"encoding/json"
22-
2322
"errors"
2423
"net/http"
2524

@@ -61,6 +60,8 @@ func (h *defaulterForType) Handle(ctx context.Context, req Request) Response {
6160
panic("object should never be nil")
6261
}
6362

63+
ctx = NewContextWithRequest(ctx, req)
64+
6465
// Get the object in the request
6566
obj := h.object.DeepCopyObject()
6667
if err := h.decoder.Decode(req, obj); err != nil {

pkg/webhook/admission/validator_custom.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,8 @@ func (h *validatorForType) Handle(ctx context.Context, req Request) Response {
6464
panic("object should never be nil")
6565
}
6666

67+
ctx = NewContextWithRequest(ctx, req)
68+
6769
// Get the object in the request
6870
obj := h.object.DeepCopyObject()
6971

pkg/webhook/admission/webhook.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -253,3 +253,21 @@ func StandaloneWebhook(hook *Webhook, opts StandaloneOptions) (http.Handler, err
253253
}
254254
return metrics.InstrumentedHook(opts.MetricsPath, hook), nil
255255
}
256+
257+
// requestContextKey is how we find the admission.Request in a context.Context.
258+
type requestContextKey struct{}
259+
260+
// RequestFromContext returns an admission.Request from ctx.
261+
func RequestFromContext(ctx context.Context) (Request, error) {
262+
if v, ok := ctx.Value(requestContextKey{}).(Request); ok {
263+
return v, nil
264+
}
265+
266+
return Request{}, errors.New("admission.Request not found in context")
267+
}
268+
269+
// NewContextWithRequest returns a new Context, derived from ctx, which carries the
270+
// provided admission.Request.
271+
func NewContextWithRequest(ctx context.Context, req Request) context.Context {
272+
return context.WithValue(ctx, requestContextKey{}, req)
273+
}

0 commit comments

Comments
 (0)