Debian Codegraph @

pkg/endpoints/request/context.go

raw
1 /*
2 Copyright 2014 The Kubernetes Authors.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 package request
18
19 import (
20 "context"
21
22 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
23 "k8s.io/apiserver/pkg/authentication/user"
24 )
25
26 // The key type is unexported to prevent collisions
27 type key int
28
29 const (
30 // namespaceKey is the context key for the request namespace.
31 namespaceKey key = iota
32
33 // userKey is the context key for the request user.
34 userKey
35 )
36
37 // NewContext instantiates a base context object for request flows.
38 func NewContext() context.Context {
39 return context.TODO()
40 }
41
42 // NewDefaultContext instantiates a base context object for request flows in the default namespace
43 func NewDefaultContext() context.Context {
44 return WithNamespace(NewContext(), metav1.NamespaceDefault)
45 }
46
47 // WithValue returns a copy of parent in which the value associated with key is val.
48 func WithValue(parent context.Context, key interface{}, val interface{}) context.Context {
49 return context.WithValue(parent, key, val)
50 }
51
52 // WithNamespace returns a copy of parent in which the namespace value is set
53 func WithNamespace(parent context.Context, namespace string) context.Context {
54 return WithValue(parent, namespaceKey, namespace)
55 }
56
57 // NamespaceFrom returns the value of the namespace key on the ctx
58 func NamespaceFrom(ctx context.Context) (string, bool) {
59 namespace, ok := ctx.Value(namespaceKey).(string)
60 return namespace, ok
61 }
62
63 // NamespaceValue returns the value of the namespace key on the ctx, or the empty string if none
64 func NamespaceValue(ctx context.Context) string {
65 namespace, _ := NamespaceFrom(ctx)
66 return namespace
67 }
68
69 // WithUser returns a copy of parent in which the user value is set
70 func WithUser(parent context.Context, user user.Info) context.Context {
71 return WithValue(parent, userKey, user)
72 }
73
74 // UserFrom returns the value of the user key on the ctx
75 func UserFrom(ctx context.Context) (user.Info, bool) {
76 user, ok := ctx.Value(userKey).(user.Info)
77 return user, ok
78 }