Skip to content

Commit

Permalink
feat: add Go modules and timeout handling examples
Browse files Browse the repository at this point in the history
- Add `go.mod` file for module initialization in solution01
- Implement a basic Go program in solution01 to demonstrate handling timeouts with `time.After`
- Add `go.mod` file for module initialization in solution02
- Implement a basic Go program in solution02 to demonstrate handling timeouts with `context.WithTimeout`

Signed-off-by: appleboy <[email protected]>
  • Loading branch information
appleboy committed Dec 21, 2024
1 parent 9b897fa commit b623e29
Show file tree
Hide file tree
Showing 4 changed files with 80 additions and 0 deletions.
3 changes: 3 additions & 0 deletions example56-context-timeout/solution01/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module example

go 1.23.1
37 changes: 37 additions & 0 deletions example56-context-timeout/solution01/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package main

import (
"time"
)

func main() {
output := make(chan int, 30)

go func() {
for i := 0; i < 30; i++ {
output <- i
time.Sleep(100 * time.Millisecond)
}
}()

timeout := time.After(1 * time.Second)
// how to fix the timeout issue?
for {
select {
case val := <-output:
select {
case <-timeout:
println("reached timeout, but still have data to process")
return
default:
}
// simulate slow consumer
time.Sleep(500 * time.Millisecond)
println("output:", val)
// how to fix the timeout issue?
case <-timeout:
println("timeout")
return
}
}
}
3 changes: 3 additions & 0 deletions example56-context-timeout/solution02/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module example

go 1.23.1
37 changes: 37 additions & 0 deletions example56-context-timeout/solution02/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package main

import (
"context"
"time"
)

func main() {
output := make(chan int, 30)

go func() {
for i := 0; i < 30; i++ {
output <- i
time.Sleep(100 * time.Millisecond)
}
}()

ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
// how to fix the timeout issue?
for {
select {
case val := <-output:
if ctx.Err() != nil {
println("reached timeout, but still have data to process")
return
}
// simulate slow consumer
time.Sleep(500 * time.Millisecond)
println("output:", val)
// how to fix the timeout issue?
case <-ctx.Done():
println("timeout")
return
}
}
}

0 comments on commit b623e29

Please sign in to comment.