How to notify a handler?

To notify a handler in Go, you can use channels to communicate between goroutines. Here's a simple example demonstrating how to notify a handler when a task is completed:

package main

import (
	"fmt"
	"time"
)

// This function simulates a worker that performs some work.
func worker(done chan bool) {
	fmt.Print("working...")
	time.Sleep(time.Second) // Simulate work with sleep
	fmt.Println("done")

	// Notify that the work is done
	done <- true
}

func main() {
	// Create a channel to notify when the worker is done
	done := make(chan bool, 1)

	// Start the worker goroutine
	go worker(done)

	// Wait for the notification from the worker
	<-done

	// Call the handler after receiving the notification
	handler()
}

// Example handler function
func handler() {
	fmt.Println("Handler notified and executed.")
}

In this example, the worker function performs some work and sends a notification through the done channel when it's finished. The main function waits for this notification before calling the handler function.

0 Comments

no data
Be the first to share your comment!