@kjk1/

gobook context with value

Go

No description

fork
loading
Files
  • main.go

This Plugin Crashed!

Error: Error: must not create an existing file {"type":"CREATE_FILE","wid":"0.18322106160442853","path":"main.go","file":{"path":"main.go","content":{"asEncoding":{"base64":"cGFja2FnZSBtYWluCgppbXBvcnQgKAoJImNvbnRleHQiCgkiZm10IgopCgovLyA6c2hvdyBzdGFydAp0eXBlIFVzZXIgc3RydWN0IHsKCU5hbWUgICAgICAgc3RyaW5nCglJc0xvZ2dlZEluIGJvb2wKfQoKdHlwZSB1c2VyS2V5VHlwZSBpbnQKCnZhciB1c2VyS2V5IHVzZXJLZXlUeXBlCgpmdW5jIGNvbnRleHRXaXRoVXNlcihjdHggY29udGV4dC5Db250ZXh0LCB1c2VyICpVc2VyKSBjb250ZXh0LkNvbnRleHQgewoJcmV0dXJuIGNvbnRleHQuV2l0aFZhbHVlKGN0eCwgdXNlcktleSwgdXNlcikKfQoKLy8gcmV0dXJucyBuaWwgaWYgbm90IHNldApmdW5jIGdldFVzZXJGcm9tQ29udGV4dChjdHggY29udGV4dC5Db250ZXh0KSAqVXNlciB7Cgl1c2VyLCBvayA6PSBjdHguVmFsdWUodXNlcktleSkuKCpVc2VyKQoJaWYgIW9rIHsKCQlyZXR1cm4gbmlsCgl9CglyZXR1cm4gdXNlcgp9CgovLyB3aWxsIHBhbmljIGlmIG5vdCBzZXQKZnVuYyBtdXN0R2V0VXNlckZyb21Db250ZXh0KGN0eCBjb250ZXh0LkNvbnRleHQpICpVc2VyIHsKCXJldHVybiBjdHguVmFsdWUodXNlcktleSkuKCpVc2VyKQp9CgpmdW5jIHByaW50VXNlcihjdHggY29udGV4dC5Db250ZXh0KSB7Cgl1c2VyIDo9IGdldFVzZXJGcm9tQ29udGV4dChjdHgpCglmbXQuUHJpbnRmKCJVc2VyOiAlI3ZcbiIsIHVzZXIpCn0KCmZ1bmMgbWFpbigpIHsKCWN0eCA6PSBjb250ZXh0LkJhY2tncm91bmQoKQoJdXNlciA6PSAmVXNlcnsKCQlOYW1lOiAgICAgICAiSm9obiIsCgkJSXNMb2dnZWRJbjogZmFsc2UsCgl9CgljdHggPSBjb250ZXh0V2l0aFVzZXIoY3R4LCB1c2VyKQoKCXByaW50VXNlcihjdHgpCn0KCi8vIDpzaG93IGVuZA=="},"asBuffer":null},"loaded":true}}
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