When debugging a program that makes use of say context.WithTimeout
when you are not stepping through lines the clock keeps ticking, so before you can debug code piece that depends on given context, that context becomes done thus the code piece you are interested in debugging does not execute. For example in the following snippet I have to increase the timestamp
value to be able to step through do()
and retry()
because otherwise timeout will be reached way before I can do it:
package main
import (
"context"
"fmt"
"math/rand"
"time"
)
const success = 0.1
const timeframe = time.Microsecond * 2
func main() {
ctx, cancel := context.WithTimeout(context.Background(), timeframe)
do(ctx, cancel)
}
func do(ctx context.Context, cancel context.CancelFunc) {
defer retry(ctx, cancel)
select {
case <-ctx.Done(): // timeout will be reached before i reach this line
panic("fail")
default:
if rand.Float64() < success {
cancel()
fmt.Println("success")
return
} else {
fmt.Println("fail")
}
}
func retry(ctx context.Context, cancel context.CancelFunc) {
r := recover()
if r == nil {
do(ctx, cancel)
}
}
I haven't used English that much to talk about programming and tech so, feel free to ask to rephrase.