Skip to content

Commit 066c204

Browse files
committed
Update README.md
1 parent b1c64c4 commit 066c204

File tree

1 file changed

+20
-13
lines changed

1 file changed

+20
-13
lines changed

README.md

Lines changed: 20 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -58,15 +58,18 @@ if err = (&pod.Webhook{}).SetupWebhookWithManager(mgr); err != nil {
5858
```
5959

6060
## Examples
61-
### Mutating admission webhook using `MutateObjectByFunc`
61+
### Mutating admission webhook using `MutateObjectFunc`
62+
The `MutateObjectFunc` creates the JSON patches for admission response automatically in order to simplify the mutation of `runtime.Object`.
63+
The example shows how the functional `MutateObjectFunc` interface can be used to mutate a `Pod`.
6264
```go
6365
package pod
6466

6567
import (
6668
"context"
67-
69+
6870
corev1 "k8s.io/api/core/v1"
6971
"k8s.io/apimachinery/pkg/runtime"
72+
"sigs.k8s.io/controller-runtime/pkg/client"
7073
"sigs.k8s.io/controller-runtime/pkg/log"
7174
"sigs.k8s.io/controller-runtime/pkg/manager"
7275
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
@@ -75,24 +78,28 @@ import (
7578
)
7679

7780
type Webhook struct {
78-
webhook.MutatingWebhook
81+
mutator *webhook.MutateObjectFunc
7982
}
8083

8184
func (w *Webhook) SetupWebhookWithManager(mgr manager.Manager) error {
85+
w.mutator = &webhook.MutateObjectFunc{
86+
Func: func(ctx context.Context, request admission.Request, object runtime.Object) error {
87+
return w.Mutate(ctx, request, object)
88+
},
89+
}
90+
8291
return webhook.NewGenericWebhookManagedBy(mgr).
8392
For(&corev1.Pod{}).
84-
Complete(w)
93+
Complete(w.mutator)
8594
}
8695

87-
func (w *Webhook) Mutate(ctx context.Context, req admission.Request) admission.Response {
88-
return webhook.MutateObjectByFunc(ctx, req, func(ctx context.Context, request admission.Request, object runtime.Object) error {
89-
_ = log.FromContext(ctx)
96+
func (w *Webhook) Mutate(ctx context.Context, request admission.Request, object runtime.Object) error {
97+
_ = log.FromContext(ctx)
98+
99+
pod := object.(*corev1.Pod)
100+
// TODO add your programmatic mutation logic here
101+
object = pod
90102

91-
pod := object.(*corev1.Pod)
92-
// TODO add your programmatic mutation logic here
93-
object = pod
94-
95-
return nil
96-
})
103+
return nil
97104
}
98105
```

0 commit comments

Comments
 (0)