Skip to content

Instantly share code, notes, and snippets.

@ostretsov
Created July 22, 2023 03:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ostretsov/17901c8d6c73ba69c39ab48013c35be2 to your computer and use it in GitHub Desktop.
Save ostretsov/17901c8d6c73ba69c39ab48013c35be2 to your computer and use it in GitHub Desktop.
package main
import (
"context"
"fmt"
"regexp"
"time"
)
func Example_contextHierarchy() {
ctxV1 := context.WithValue(context.Background(), "foo", "bar")
ctxV2 := context.WithValue(ctxV1, "foo", "baz")
addrRe := regexp.MustCompile("0x[0-9a-f]+")
vCtx := fmt.Sprintf("%#v", ctxV2)
vCtx = addrRe.ReplaceAllString(vCtx, "0x0000000000")
fmt.Println(vCtx)
ctxCancel, cancel := context.WithCancel(ctxV2)
defer cancel()
cCtx := fmt.Sprintf("%#v", ctxCancel)
cCtx = addrRe.ReplaceAllString(cCtx, "0x0000000000")
fmt.Println(cCtx)
ctxDeadline, cancelDeadline := context.WithDeadline(ctxV2, time.Now().Add(1*time.Hour))
defer cancelDeadline()
dCtx := fmt.Sprintf("%#v", ctxDeadline)
dCtx = addrRe.ReplaceAllString(dCtx, "0x0000000000")
dCtx = regexp.MustCompile("ext:[0-9]+").ReplaceAllString(dCtx, "ext:0000000000000")
fmt.Println(dCtx)
// Output:
// &context.valueCtx{Context:(*context.valueCtx)(0x0000000000), key:"foo", val:"baz"}
// &context.cancelCtx{Context:(*context.valueCtx)(0x0000000000), mu:sync.Mutex{state:0, sema:0x0000000000}, done:atomic.Value{v:interface {}(nil)}, children:map[context.canceler]struct {}(nil), err:error(nil), cause:error(nil)}
// &context.timerCtx{cancelCtx:(*context.cancelCtx)(0x0000000000), timer:(*time.Timer)(0x0000000000), deadline:time.Time{wall:0x0000000000, ext:0000000000000, loc:(*time.Location)(0x0000000000)}}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment