Created
April 11, 2017 14:51
-
-
Save johnmccabe/4e3d8ee84d15cb6bffb709ae660c9e2a to your computer and use it in GitHub Desktop.
Dealing with Timeout via a buffered error channel
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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