Skip to content

Commit 413edf8

Browse files
committed
add admissionRequest in ctx
1 parent 696cac8 commit 413edf8

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

Diff for: apis/contexts.go

+17
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import (
2222

2323
authenticationv1 "k8s.io/api/authentication/v1"
2424
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
25+
admissionv1 "k8s.io/api/admission/v1"
2526
)
2627

2728
// This is attached to contexts passed to webhook interfaces when
@@ -245,6 +246,7 @@ func IsDryRun(ctx context.Context) bool {
245246
// This is attached to contexts passed to webhook interfaces with
246247
// additional context from the HTTP request.
247248
type httpReq struct{}
249+
type AdmissionReq struct{}
248250

249251
// WithHTTPRequest associated the HTTP request object the webhook
250252
// received with the context.
@@ -260,3 +262,18 @@ func GetHTTPRequest(ctx context.Context) *http.Request {
260262
}
261263
return v.(*http.Request)
262264
}
265+
266+
// WithAdmissionRequest associated the admissionv1.AdmissionRequest object the webhook
267+
// received with the context.
268+
func WithAdmissionRequest(ctx context.Context, r *admissionv1.AdmissionRequest) context.Context {
269+
return context.WithValue(ctx, AdmissionReq{}, r)
270+
}
271+
272+
// GetAdmissionRequest fetches the admissionv1.AdmissionRequest received by the webhook.
273+
func GetAdmissionRequest(ctx context.Context) *admissionv1.AdmissionRequest {
274+
v := ctx.Value(AdmissionReq{})
275+
if v == nil {
276+
return nil
277+
}
278+
return v.(*admissionv1.AdmissionRequest)
279+
}

Diff for: apis/contexts_test.go

+19
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import (
2424
"github.com/google/go-cmp/cmp"
2525
authenticationv1 "k8s.io/api/authentication/v1"
2626
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
27+
admissionv1 "k8s.io/api/admission/v1"
2728
)
2829

2930
func TestContexts(t *testing.T) {
@@ -241,3 +242,21 @@ func TestGetHTTPRequest(t *testing.T) {
241242
t.Errorf("GetHTTPRequest() = %v, wanted %v", got, want)
242243
}
243244
}
245+
246+
func TestGetAdmissionRequest(t *testing.T) {
247+
ctx := context.Background()
248+
249+
if got := GetAdmissionRequest(ctx); got != nil {
250+
t.Errorf("GetAdmissionRequest() = %v, wanted %v", got, nil)
251+
}
252+
253+
admReq := admissionv1.AdmissionRequest{
254+
Name: "foo",
255+
}
256+
ctx = WithAdmissionRequest(ctx, &admReq)
257+
258+
if want, got := &admReq, GetAdmissionRequest(ctx); got != want {
259+
t.Errorf("GetAdmissionRequest() = %v, wanted %v", got, want)
260+
}
261+
}
262+

0 commit comments

Comments
 (0)