github.com/aacfactory/fns@v1.2.86-0.20240310083819-80d667fc0a17/context/value.go (about) 1 /* 2 * Copyright 2023 Wang Min Xiang 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 18 package context 19 20 import ( 21 "github.com/aacfactory/errors" 22 "github.com/aacfactory/fns/commons/objects" 23 ) 24 25 func UserValue[T any](ctx Context, key []byte) (v T, has bool, err error) { 26 vv := ctx.UserValue(key) 27 if vv == nil { 28 return 29 } 30 v, has = vv.(T) 31 if has { 32 return 33 } 34 v, err = objects.Value[T](objects.New(vv)) 35 if err != nil { 36 err = errors.Warning("fns: get context user value failed").WithCause(err).WithMeta("key", string(key)) 37 return 38 } 39 has = true 40 return 41 } 42 43 func LocalValue[T any](ctx Context, key []byte) (v T, has bool) { 44 vv := ctx.LocalValue(key) 45 if vv == nil { 46 return 47 } 48 v, has = vv.(T) 49 return 50 } 51 52 func Value[T any](ctx Context, key any) (v T, has bool) { 53 vv := ctx.Value(key) 54 if vv == nil { 55 return 56 } 57 v, has = vv.(T) 58 return 59 } 60 61 type valueContext struct { 62 Context 63 key any 64 val any 65 } 66 67 func (c *valueContext) Value(key any) any { 68 if c.key == key { 69 return c.val 70 } 71 return c.Context.Value(key) 72 }