DEV Community

urgensherpa
urgensherpa

Posted on

2 1

Context

#go

Context allow you to send cancellation signal to asynchronous process/ go-routine.
context

Methods provided by context interface:-

Value(key) This method returns the value associated with the specified key.

**Done() **This method returns a channel that can be used to receive a cancelation notification.

Deadline() This method returns the Time that represents the deadline for the request and a bool value that will be false if no deadline has been specified.

Err() This method returns an error that indicates why the Done channel received a signal. The context package defines two variables that can be used to compare the error: Canceled indicates that the request was canceled, and DeadlineExeeded indicates that the deadline passed.

Functions https://pkg.go.dev/context#pkg-functions

  • Background()
  • WithCancel(ctx)
  • WithDeadline(ctx,time)
  • WithTimeout(ctx,duration)
  • WithValue(ctx, key,val)
package main

import (
    "sync"
    "time"
    "fmt"
    "context"
)

func processRequest(ctx context.Context, wg *sync.WaitGroup, count int) {
    total := 0
    for i := 0; i < count; i++ {
        select {
        case <-ctx.Done():
            fmt.Println("Stopping processing - request cancelled")
            goto end
        default:
            fmt.Printf("Processing request: %v \n", total)
            total++
            time.Sleep(time.Millisecond * 250)
        }
    }
    fmt.Println("%v Request processed...", total)
end:
    wg.Done()
}
func main() {
    waitGroup := sync.WaitGroup{}
    waitGroup.Add(1)
    fmt.Println("Request dispatched...")
    ctx, cancel := context.WithCancel(context.Background())

    go processRequest(ctx, &waitGroup, 10)
    time.Sleep(time.Second)
    fmt.Println("Canceling req")
        cancel()
    waitGroup.Wait()

}

---

% go run contxt.go
Request dispatched...
Processing request: 0 
Processing request: 1 
Processing request: 2 
Processing request: 3 
Canceling request
Stopping processing - request cancelled
Enter fullscreen mode Exit fullscreen mode

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay