Skip to content

Instantly share code, notes, and snippets.

@johnmccabe
Created April 11, 2017 14:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnmccabe/4e3d8ee84d15cb6bffb709ae660c9e2a to your computer and use it in GitHub Desktop.
Save johnmccabe/4e3d8ee84d15cb6bffb709ae660c9e2a to your computer and use it in GitHub Desktop.
Dealing with Timeout via a buffered error channel
package main
import (
"fmt"
"log"
"time"
)
func work() error {
for i := 0; i < 1000; i++ {
select {
case <-time.After(2 * time.Second):
if i == 2 {
return fmt.Errorf("Done gone fucked up bai")
}
fmt.Println("Doing some work ", i)
}
}
return nil
}
func main() {
fmt.Println("Hey, I'm going to do some work")
ch := make(chan error, 1)
go func() {
ch <- work()
}()
select {
case err := <-ch:
if err != nil {
log.Fatal("Something went wrong :(", err)
}
case <-time.After(8 * time.Second):
fmt.Println("Life is to short to wait that long")
}
fmt.Println("Finished. I'm going home")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment