Fix

"send on closed channel" Panic in Go

Fix 'send on closed channel' panic by ensuring channels are closed only once and checking state before sending.

The panic occurs because your code attempts to send data on a channel that has already been closed by another goroutine or the same one. You must ensure the channel is only closed once, typically by the sender after all data is sent, and receivers should check if the channel is closed before sending.

func safeSend(ch chan int, val int) {
    select {
    case ch <- val:
        // Send succeeded
    default:
        // Channel might be closed or full; handle gracefully
    }
}

Alternatively, use a sync.Once to guarantee the channel is closed exactly once:

var closeOnce sync.Once
func closeChannel(ch chan int) {
    closeOnce.Do(func() {
        close(ch)
    })
}

Always verify channel state before sending if closure is possible.