How do I watch resources and handle events?

Go, watch resources, handle events, Golang events, resource monitoring, event handling, Go example
Learn how to watch resources and handle events in Go. This guide provides an example of resource monitoring and event handling using Golang.
package main import ( "fmt" "time" ) // Resource represents the entity to be monitored type Resource struct { ID string Value int } // Watcher watches for changes in resources type Watcher struct { resources map[string]*Resource onChange func(resource *Resource) } // NewWatcher creates a new watcher func NewWatcher(onChange func(resource *Resource)) *Watcher { return &Watcher{ resources: make(map[string]*Resource), onChange: onChange, } } // UpdateResource updates the resource and triggers the event func (w *Watcher) UpdateResource(resource *Resource) { w.resources[resource.ID] = resource w.onChange(resource) } func main() { watcher := NewWatcher(func(resource *Resource) { fmt.Printf("Resource updated: ID=%s, Value=%d\n", resource.ID, resource.Value) }) go func() { for { time.Sleep(2 * time.Second) watcher.UpdateResource(&Resource{ID: "1", Value: newValue()}) } }() select {} // Keep the main routine alive } func newValue() int { return int(time.Now().UnixNano() % 100) // Mock value generation }

Go watch resources handle events Golang events resource monitoring event handling Go example