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.