Files
  • main.go
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package main

import (
	"context"
	"fmt"
)

// :show start
type User struct {
	Name       string
	IsLoggedIn bool
}

type userKeyType int

var userKey userKeyType

func contextWithUser(ctx context.Context, user *User) context.Context {
	return context.WithValue(ctx, userKey, user)
}

// returns nil if not set
func getUserFromContext(ctx context.Context) *User {
	user, ok := ctx.Value(userKey).(*User)
	if !ok {
		return nil
	}
	return user
}

// will panic if not set
func mustGetUserFromContext(ctx context.Context) *User {
	return ctx.Value(userKey).(*User)
}

func printUser(ctx context.Context) {
	user := getUserFromContext(ctx)
	fmt.Printf("User: %#v\n", user)
}

func main() {
	ctx := context.Background()
	user := &User{
		Name:       "John",
		IsLoggedIn: false,
	}
	ctx = contextWithUser(ctx, user)

	printUser(ctx)
}

// :show end
go version go1.9.4 linux/amd64