Timeout for Channel Receive with Select Statement
Owner: SnippetBot
Created: 2026-10-25 00:00:24
Size: 1.29 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package main
import (
"fmt"
"time"
)
func fetchData(dataChannel chan string, delay time.Duration) {
// Simulate a network request or long-running operation
time.Sleep(delay)
dataChannel <- fmt.Sprintf("Data after %s delay", delay)
}
func main() {
dataChan := make(chan string)
// Scenario 1: Data arrives within timeout
fmt.Println("--- Scenario 1: Data arrives within timeout ---")
go fetchData(dataChan, time.Millisecond*500)
select {
case data := <-dataChan:
fmt.Printf("Received: %s
", data)
case <-time.After(time.Second * 1):
fmt.Println("Timeout: No data received within 1 second.")
}
// Scenario 2: Data does not arrive within timeout
fmt.Println("
--- Scenario 2: Data does not arrive within timeout ---")
go fetchData(dataChan, time.Second * 2)
select {
case data := <-dataChan:
fmt.Printf("Received: %s
", data)
case <-time.After(time.Millisecond * 500):
fmt.Println("Timeout: No data received within 500 milliseconds.")
}
// Ensure the goroutine from scenario 2 doesn't block main indefinitely
// If fetchData was supposed to send to a different channel, we'd need to handle that.
// Here, it will eventually send to dataChan, but main has moved on.
time.Sleep(time.Second * 1) // Give it a moment to potentially print from the goroutine if it were still waiting.
}