liveBook · Manning

Deadline

As explained in Learn Go with Pocket-Sized Projects

Deadline is a context.Context method that reports whether a deadline is set and returns its time when present.

Deadline is a context.Context method that reports whether a deadline is set and, when present, returns its time. The deadline marks when the context begins reporting expiration. Use Done to observe completion and Err to learn why the context ended; reading Done is preferred to comparing Deadline with time.Now(). section 10.6.1

Use deadlines to control work across service boundaries:

  • Create a child context with WithDeadline for a specific timestamp or WithTimeout for a duration; WithTimeout is more common for remote calls. section 10.6.2
  • Give separate downstream calls their own child context and deadline when one request invokes multiple services, so slow calls can be identified precisely. section 10.6.3
  • Account for network latency and avoid limits that are unnecessarily strict; otherwise remote calls can hang indefinitely. section 10.6 section 10.8

Protecting a database call

Create a 100-millisecond child context before calling the repository, defer its cancellation, and pass the child to db.Add. A timeout test can block for two seconds, select on ctx.Done(), and expect context.DeadlineExceeded.

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Defines the method and contrasts it with Done, then applies per-call timeouts and tests expiration behavior.
Examples
Uses a 100-millisecond database timeout, a blocking mock, ctx.Done(), and context.DeadlineExceeded.
What it assumes
Assumes familiarity with Go functions and interfaces while defining context.Context and its methods from their documentation.
What you can do after
Apply it via context.WithTimeout, propagate the child context, and diagnose expiration through Done and Err.
How it connects
Connects context.Context with cancellation, timeouts, Done, Err, child contexts, remote calls, and mocking.

Also explained in

Compare how 3 books explain deadline →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.