In daily development we will probably encounter timeout control scenarios, such as a batch of time-consuming tasks, network requests, etc.; a good timeout control can effectively avoid some problems (such as goroutine leakage, resource non-release, etc.).
Timer
The first option is Time.After(d Duration)
: the timeout control in go is very simple.
output:
Context
The second option is to use context, which is a powerful feature of go.
Using the context.WithTimeout()
method will return a context with a timeout function.
|
|
In the same way, the Done()
function of context
returns a channel
that will take effect when the current job is done or when the context is cancelled.
|
|
The timeout.Err()
method also tells the reason for the current context
closure.
goroutine Passing context
Another advantage of using context
is that you can take advantage of the fact that it is naturally passed across multiple goroutines, so that all goroutines that pass the context receive cancellation notifications at the same time, which is very widely used in multiple go.
|
|
In the above example, no matter how many layers of goroutine
are nested, it is possible to get a message when context
is cancelled (provided that context
is passed away, of course)
You can also call the cancelFunc()
function manually when you need to cancel the context in advance in some special cases.
Case in Gin
The Shutdown(ctx)
function provided by Gin also makes full use of the context
.
For example, the above code is to wait 10s for Gin
to release its resources, which is the same principle as the above example.