DEV Community

renanbastos93
renanbastos93

Posted on

How to verify if the context has a deadline

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)
}
Enter fullscreen mode Exit fullscreen mode

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)
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

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)
    })
}
Enter fullscreen mode Exit fullscreen mode

That's what I wanted to show here. I hope this helps!

Top comments (2)

Collapse
 
dougds profile image
Douglas Oliveira

Nice and easy! Ty

Collapse
 
renanbastos93 profile image
renanbastos93

Thanks dude