context package example
This commit is contained in:
parent
575fab8956
commit
03694f398a
2 changed files with 20 additions and 1 deletions
|
|
@ -5,6 +5,25 @@ import (
|
|||
"fmt"
|
||||
)
|
||||
|
||||
func main() {
|
||||
type aKey string
|
||||
|
||||
func searchKey(ctx context.Context, k aKey) {
|
||||
v := ctx.Value(k)
|
||||
if v != nil {
|
||||
fmt.Println("found value:", v)
|
||||
return
|
||||
} else {
|
||||
fmt.Println("key not found:", k)
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
myKey := aKey("mySecretValue")
|
||||
ctx := context.WithValue(context.Background(), myKey, "mySecretValue")
|
||||
|
||||
searchKey(ctx, myKey)
|
||||
|
||||
searchKey(ctx, aKey("notThere"))
|
||||
emptyCtx := context.TODO()
|
||||
searchKey(emptyCtx, aKey("notThere"))
|
||||
}
|
||||
|
|
|
|||
|
|
@ -37,6 +37,6 @@ func main() {
|
|||
err := http.ListenAndServe(PORT, nil)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
os.Exit(10)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue