Passing scoped values

The introduction of context.Context in http.Request tries to address this issue by defining a single interface that can be assigned, recovered, and used in various handlers.

The downside is that a context isn't assigned automatically to a request, and context values cannot be recycled. There should be no really good reason to do that since the context should store data that's specific to a certain package or scope, and the packages themselves should be the only ones that are able to interact with them.

A good pattern is the usage of a unique unexported key type combined with auxiliary functions to get or set a certain value:

type keyType struct{}

var key = &keyType{}

func WithKey(ctx context.Context, value string) context.Context {
return context.WithValue(ctx, key, value)
}

func GetKey(ctx context.Context) (string, bool) {
v := ctx.Value(key)
if v == nil {
return "", false
}
return v.(string), true
}

A context request is the only case in the standard library where it is stored in the data structure with the WithContext method and it's accessed using the Context method. This has been done in order to not break the existing code, and maintain the promise of compatibility of Go 1.

The full example is available here: https://play.golang.org/p/W6gGp_InoMp.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.135.80