Skip to content

Instantly share code, notes, and snippets.

@arschles

arschles/get_with_retry.go

Last active Apr 15, 2019
Embed
What would you like to do?
GetWithRetry
package main
import (
"context"
"fmt"
"time"
)
// adaptation of
// https://github.com/Azure/aks-engine/blob/f61205726c139d286c427b3403942a079eb1b26d/test/e2e/kubernetes/pod/pod.go#L289
func doPodThings() struct{} {
// uncomment the below sleep to toggle the error codepath
// time.Sleep(3 * time.Second)
return struct{}{}
}
func main() {
ctxDur := 2 * time.Second
ctx, cancel := context.WithTimeout(context.Background(), ctxDur)
defer cancel()
ch := make(chan struct{})
go func() {
for {
select {
case <-ctx.Done():
// don't send error here. it'll be returned in the
// select in the main goroutine
return
case ch <- doPodThings():
}
}
}()
// you return on the chan receive so you don't need a loop here
for {
select {
case <-ch:
// you would return the pod here
fmt.Println("yay!")
case <-ctx.Done():
// this is where you return the error
fmt.Println("oh noes! timeout after", ctxDur)
return
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.