<p>I want to watch Kubernetes pod events for a certain application.</p>
<p>I went with NewSharedInformerFactoryWithOptions. I have added appropriate labels selector, But it is not getting filtered out. As I want to filter it using the label: 'app=nats-box'</p>
<p>Here is the code -</p>
<pre><code>req, err := labels.NewRequirement(&quot;app&quot;, selection.Equals, []string{&quot;nats-box&quot;})
    if err != nil {
        log.Fatalf(&quot;error %s, bad requirement&quot;, err.Error())
    }
selector := labels.NewSelector()
selector.Add(*req)

filteredFactory := informers.NewSharedInformerFactoryWithOptions(clientset, 0, informers.WithNamespace(&quot;default&quot;), informers.WithTweakListOptions(func(options *metav1.ListOptions) {
    options.LabelSelector = selector.String()
}))

podInformer := filteredFactory.Core().V1().Pods().Informer()

podInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{
    AddFunc: func(obj interface{}) {
        fmt.Println(&quot;pod add&quot;)
        name := obj.(*corev1.Pod).Name
        labels := obj.(*corev1.Pod).Labels
        fmt.Printf(&quot;pod Name: %s\nLabels - %v\n\n&quot;, name, labels)
    })
</code></pre>
<p>I get the output for all the pods, the namespace is getting filtered but not the labels. Not able to figure out where I am making the mistake.</p>

ankit
<p>You can directly provide the label string in the <code>opts.LabelSelector</code>:</p>
<pre><code>labelOptions := informers.WithTweakListOptions(func(opts *metav1.ListOptions) {
    opts.LabelSelector = &quot;app=nats-box&quot;
})
factory := informers.NewSharedInformerFactoryWithOptions(clientset, 0, informers.WithNamespace(&quot;default&quot;) ,labelOptions)
informer := factory.Core().V1().Pods().Informer()
stopper := make(chan struct{})
defer close(stopper)
informer.AddEventHandler(cache.ResourceEventHandlerFuncs{
    AddFunc: func(obj interface{}) {
        fmt.Println(&quot;pod add&quot;)
        name := obj.(*corev1.Pod).Name
        labels := obj.(*corev1.Pod).Labels
        fmt.Printf(&quot;pod Name: %s\nLabels - %v\n\n&quot;, name, labels)
    },
})
informer.Run(stopper)
</code></pre>
