|
| 1 | +/* |
| 2 | +Copyright 2018 The Kubernetes Authors. |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +package webhook_test |
| 18 | + |
| 19 | +import ( |
| 20 | + "context" |
| 21 | + |
| 22 | + ctrl "sigs.k8s.io/controller-runtime" |
| 23 | + . "sigs.k8s.io/controller-runtime/pkg/webhook" |
| 24 | + "sigs.k8s.io/controller-runtime/pkg/webhook/admission" |
| 25 | +) |
| 26 | + |
| 27 | +var ( |
| 28 | + mgr ctrl.Manager |
| 29 | +) |
| 30 | + |
| 31 | +func Example() { |
| 32 | + // Build webhooks |
| 33 | + // These handlers could be also be implementations |
| 34 | + // of the AdmissionHandler interface for more complex |
| 35 | + // implementations. |
| 36 | + mutatingHook := &Admission{ |
| 37 | + Handler: admission.HandlerFunc(func(ctx context.Context, req AdmissionRequest) AdmissionResponse { |
| 38 | + return Patched("some changes", |
| 39 | + JSONPatchOp{Operation: "add", Path: "/metadata/annotations/access", Value: "granted"}, |
| 40 | + JSONPatchOp{Operation: "add", Path: "/metadata/annotations/reason", Value: "not so secret"}, |
| 41 | + ) |
| 42 | + }), |
| 43 | + } |
| 44 | + |
| 45 | + validatingHook := &Admission{ |
| 46 | + Handler: admission.HandlerFunc(func(ctx context.Context, req AdmissionRequest) AdmissionResponse { |
| 47 | + return Denied("none shall pass!") |
| 48 | + }), |
| 49 | + } |
| 50 | + |
| 51 | + // Create a webhook server. |
| 52 | + hookServer := &Server{ |
| 53 | + Port: 8443, |
| 54 | + } |
| 55 | + mgr.Add(hookServer) |
| 56 | + |
| 57 | + // Register the webhooks in the server. |
| 58 | + hookServer.Register("/mutating", mutatingHook) |
| 59 | + hookServer.Register("/validating", validatingHook) |
| 60 | + |
| 61 | + // Start the server by starting a previously-set-up manager |
| 62 | + err := mgr.Start(ctrl.SetupSignalHandler()) |
| 63 | + if err != nil { |
| 64 | + // handle error |
| 65 | + panic(err) |
| 66 | + } |
| 67 | +} |
0 commit comments