Types of Contexts

Learn via video courses
Topics Covered

Overview

Context package is specified as a type that, in a chained model, defines and transports Deadlines, Cancel Signals, and other Request-scoped Values. It is a standard package, mainly used for handling requests.

What are the Different Types of Context in Golang?

Contexts are essentially a packet of information that is communicated among the various layers of your application. When an API request is made, your parcel is typically produced at the application's end. This package will be moved from your service layer to your storage layer after that.

This package initially includes a few crucial components of functioning, namely:

  • The capacity to store additional data that can be distributed across the chain.
  • Controlling cancellation allows you to write bundles that function as ticking time bombs and halt code execution if it goes past a predetermined deadline or timeout value.

Context, an interface, is the major component of the package. It simply uses four techniques:

Here,

  • Deadline: returns a Boolean that is false if there is no deadline and the time at which the context should be cancelled.
  • Done: returns an empty struct receive-only channel that indicates when the context should be cancelled.
  • Err: returns nil if the done channel is open and the cause of the context cancellation if it is closed.
  • Value: Provides a value for the current context's key, or nil if the key's value is null.

In contrast with the other standard library interfaces, which often only contain one or two methods, the context has a large number of methods. They are related in three ways: When a deadline approaches, you can cancel. When the context is finished, signals are sent. Err provides the cancellation's root cause. Value, the final method, returns the value connected to a specific key. The remainder of the package consists of several functions that let you build various contexts.

Deadlines

Context.WithDeadline

In some high-performance systems, you could be required to respond within a certain amount of time. We had around 2 seconds in our system at a prior employer of mine to respond, or else the action would fail.

Context struct includes some of the functionality we require to manage how our system responds when a deadline is exceeded.

Output:

Explanation: You'll see that the doSomethingCool function contains a for loop that mimics a lengthy operation. In this, we continuously monitor the parent context object's Done channel to see if it has been closed due to a timeout. If it hasn't, we continue to print doing something nice every half-second until the timeout is reached.

Context.WithTimeout

When making external requests, such as database queries or data requests from other services via HTTP or gRPC, timeouts are a very typical pattern (both support contexts). Utilizing the context package makes handling certain instances very simple. Calling the function context is all that is necessary. Context and the actual timeout with the WithTimeout(ctx, time) method are as follows:

You still have the option to manually activate the cancel function. It operates similarly to a typical context cancellation. The behavior in this situation is quite simple. The context is cancelled if the timeout is reached. It functions essentially the same as in the previous example in the case of an HTTP call.

Cancellation Signals

When using the Deadlines, we can manually halt the context at any time by using the cancel() function, which is always returned as part of the deadlines and is available on both. However, to use the cancel function without a context, you need one. WithCancel()` is a context type that has no timeout or duration restrictions.

Context.WithCancel

To use context, we require a parent of type context for WithCancel. A context type that will return a context. Context as well as context.CancelFunc().

Example:

Output:

Explanation: To utilize the gen method in this example, you must cancel the context as soon as they are consuming the numbers to prevent leakage in the goroutines internally. In the code above, gen generates integer n in a separate goroutine and sends them to the returned channel.

Request-Scoped Values

The WithValue function makes a clone of the parent context with the specified value and the given key attached. It should not be used for other scopes, such as optional function parameters, because its scope only stores values that are pertinent to a single request while it is being handled.

Since two separate packages that use context could overwrite each other's values, the key should be something that can be compared. It's also a good idea to stay away from string values. Utilizing user-defined concrete types like struct is advised.

Context.WithValue

Output:

Explanation: After setting the context.WithValue Passed in parent context with Value, the kind of control you have when you utilize context in your request and response. Background and added a sessionID key with the value of the SESSIONID. By attaching this context to all our requests, we can easily obtain the sessionID and even cause a cancel or timeout easily.

Conclusion

  • Context package is specified as a type that, in a chained model, defines and transports Deadlines, Cancel Signals, and other Request-scoped Values.
  • This package initially includes a few crucial components of functioning, namely:
    • The capacity to store additional data that can be distributed across the chain.
    • Controlling cancellation allows you to write bundles that function as ticking time bombs and halt code execution if it goes past a predetermined deadline or timeout value.
    • Context, an interface, is the major component of the package.
  • In contrast with the other standard library interfaces, which often only contain one or two methods, the context has a large number of methods. They are related in three ways:
    • When a deadline approaches, you can cancel.
    • When the context is finished, done signals are sent.
    • Err provides the cancellation's root cause.
    • Value, the final method, returns the value connected to a specific key. The remainder of the package consists of several functions that let you build various contexts.