Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting timeout value from Go's context

Tags:

go

How to get how long duration set for timeout in context.

example:

func f(ctx context.Context) {
    // get ctx timeout value
}

func main() {
    ctx, cancel := context.WithTimeout(context.Background(),2*time.Second)
    defer cancel()
    f(ctx)
}

How to get the duration 2*time.Second from within the function f?

like image 798
Jake Muller Avatar asked Aug 31 '25 20:08

Jake Muller


1 Answers

If the func f is called immediately then the time until it times out is the time just set so you can get it by looking at the deadline

package main

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

func f(ctx context.Context) {    
         deadline,_:=ctx.Deadline()
         fmt.Println(time.Until(deadline))
    // get ctx timeout value
}

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
    defer cancel()
    f(ctx)
}

https://play.golang.org/p/n3lZJAMdLYs

like image 104
Vorsprung Avatar answered Sep 03 '25 20:09

Vorsprung