DEV Community

renanbastos93
renanbastos93

Posted on

10 2

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!

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (2)

Collapse
 
dougds profile image
Douglas Oliveira

Nice and easy! Ty

Collapse
 
renanbastos93 profile image
renanbastos93

Thanks dude

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay