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!

👋 While you are here

Reinvent your career. Join DEV.

It takes one minute and is worth it for your career.

Get started

Top comments (2)

Collapse
 
dougds profile image
Douglas Oliveira •

Nice and easy! Ty

Collapse
 
renanbastos93 profile image
renanbastos93 •

Thanks dude

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay