It's very simple, context.Context
has a little method called Deadline that returns (deadline time.Time, ok bool)
. When the ok variable is true, the deadline is set. Why use a deadline? We need to use it to set a time to cancel the operation, e.g. we need to wait for max 3 seconds to execute a query on the database, in case overtakes the time, context will call cancel in the operation.
See the example below:
func something(ctx context.Context) (context.Context, context.CancelFunc) {
if _, hasDeadline := ctx.Deadline(); !hasDeadline {
return context.WithTimeout(ctx, time.Minute)
}
return context.WithCancel(ctx)
}
Now, let's see an example using this method in an operation that prints a message many times.
func usingSomething() {
ctx, cancel := something(context.Background())
defer cancel()
for {
select {
case <-ctx.Done():
return
default:
fmt.Println("something message!")
time.Sleep(time.Second)
}
}
}
Well, I believe that it’s interesting to share the unit test as well.
func TestSomethingWithDeadline(t *testing.T) {
t.Run("using timeout of 1s", func(t *testing.T) {
ctx, _ := context.WithTimeout(context.Background(), time.Second)
ctx, cancel := something(ctx)
defer cancel()
_, hasDeadline := ctx.Deadline()
assert.EqualValues(t, true, hasDeadline)
})
}
func TestSomethingWithoutDeadline(t *testing.T) {
t.Run("using default timeout of something method", func(t *testing.T) {
ctx, cancel := something(context.Background())
defer cancel()
_, hasDeadline := ctx.Deadline()
assert.EqualValues(t, true, hasDeadline)
})
}
That's what I wanted to show here. I hope this helps!
Top comments (2)
Nice and easy! Ty
Thanks dude