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:
funcsomething(ctxcontext.Context)(context.Context,context.CancelFunc){if_,hasDeadline:=ctx.Deadline();!hasDeadline{returncontext.WithTimeout(ctx,time.Minute)}returncontext.WithCancel(ctx)}
Now, let's see an example using this method in an operation that prints a message many times.
funcusingSomething(){ctx,cancel:=something(context.Background())defercancel()for{select{case<-ctx.Done():returndefault:fmt.Println("something message!")time.Sleep(time.Second)}}}
Well, I believe that it’s interesting to share the unit test as well.
funcTestSomethingWithDeadline(t*testing.T){t.Run("using timeout of 1s",func(t*testing.T){ctx,_:=context.WithTimeout(context.Background(),time.Second)ctx,cancel:=something(ctx)defercancel()_,hasDeadline:=ctx.Deadline()assert.EqualValues(t,true,hasDeadline)})}funcTestSomethingWithoutDeadline(t*testing.T){t.Run("using default timeout of something method",func(t*testing.T){ctx,cancel:=something(context.Background())defercancel()_,hasDeadline:=ctx.Deadline()assert.EqualValues(t,true,hasDeadline)})}
That's what I wanted to show here. I hope this helps!
Top comments(2)

- Email
- LocationFlorianópolis - SC - Brazil
- EducationAnalysis and systems development
- WorkSoftware Engineer
- Joined
Thanks dude
For further actions, you may consider blocking this person and/orreporting abuse