If/Else in Go
Go: Context
In Go, a
context
is a mechanism that allows a request to be cancelled or timed out. It is commonly used to manage the lifetime of a request and its associated resources, such as database connections, network sockets, and goroutines.
A Context
carries deadlines, cancellation signals, and other request-scoped values across API boundaries and goroutines.
Context example in Go
package main
import (
"context"
"fmt"
"time"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
go doSomething(ctx)
select {
case <-ctx.Done():
fmt.Println(ctx.Err())
}
}
func doSomething(ctx context.Context) {
select {
case <-ctx.Done():
return
default:
// Do something here
}
}
In this example, we create a context with a timeout of 5 seconds using the context.WithTimeout
function. We also create a cancel function using the defer keyword to ensure it is called when the main function returns.
We then launch a goroutine to perform some task using the context. The doSomething
function checks if the context has been cancelled using the ctx.Done()
channel. If it has been cancelled, the function returns immediately. Otherwise, it performs some task.
Finally, we use a select statement to wait for the context to be cancelled. When the context is cancelled, the ctx.Err()
function returns the reason for the cancellation, which we print to the console.
Previous Article
Next Article
Golang Tutorials
- Hello World
- Operators in Go
- Declarations in Go
- Values in Go
- Variables in Go
- For in Go
- If/Else in Go
- Switch in Go
- Arrays in Go
- Slices in Go
- Maps in Go
- Range in Go
- Functions in Go
- Closures in Go
- Recursion in Go
- Pointers in Go
- Strings and Runes in Go
- Structs in Go
- Methods in Go
- Interfaces in Go
- Generics in Go
- Errors in Go
- Goroutines in Go
- Channels in Go
- Select in Go
- Timeouts in Go
- Timers in Go
- Worker Pools in Go
- WaitGroups in Go
- Mutexes in Go
- Sorting in Go
- Panic in Go
- Defer in Go
- Recover in Go
- JSON in Go
- XML in Go
- Time in Go
- Epoch in Go
- Time Formatting in Go
- Random Numbers in Go
- Number Parsing in Go
- URL Parsing in Go
- SHA256 Hashes in Go
- Base64 Encoding in Go
- Reading Files in Go
- Writing Files in Go
- File Paths in Go
- Directories in Go
- Testing and Benchmarking in Go
- Command-Line Arguments in Go
- Command-Line Flags in Go
- Command-Line Subcommands in Go
- Environment Variables in Go
- HTTP Client in Go
- HTTP Server in Go
- Context in Go
- Signals in Go