github.com/dubbogo/gost@v1.14.0/context/context.go (about)

     1  /*
     2   * Licensed to the Apache Software Foundation (ASF) under one or more
     3   * contributor license agreements.  See the NOTICE file distributed with
     4   * this work for additional information regarding copyright ownership.
     5   * The ASF licenses this file to You under the Apache License, Version 2.0
     6   * (the "License"); you may not use this file except in compliance with
     7   * the License.  You may obtain a copy of the License at
     8   *
     9   *     http://www.apache.org/licenses/LICENSE-2.0
    10   *
    11   * Unless required by applicable law or agreed to in writing, software
    12   * distributed under the License is distributed on an "AS IS" BASIS,
    13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    14   * See the License for the specific language governing permissions and
    15   * limitations under the License.
    16   */
    17  
    18  package gxcontext
    19  
    20  import (
    21  	"context"
    22  )
    23  
    24  type ValueContextKeyType int32
    25  
    26  var defaultCtxKey = ValueContextKeyType(1)
    27  
    28  type Values struct {
    29  	m map[interface{}]interface{}
    30  }
    31  
    32  func (v Values) Get(key interface{}) (interface{}, bool) {
    33  	i, b := v.m[key]
    34  	return i, b
    35  }
    36  
    37  func (c Values) Set(key interface{}, value interface{}) {
    38  	c.m[key] = value
    39  }
    40  
    41  func (c Values) Delete(key interface{}) {
    42  	delete(c.m, key)
    43  }
    44  
    45  type ValuesContext struct {
    46  	context.Context
    47  }
    48  
    49  func NewValuesContext(ctx context.Context) *ValuesContext {
    50  	if ctx == nil {
    51  		ctx = context.Background()
    52  	}
    53  
    54  	return &ValuesContext{
    55  		Context: context.WithValue(
    56  			ctx,
    57  			defaultCtxKey,
    58  			Values{m: make(map[interface{}]interface{}, 4)},
    59  		),
    60  	}
    61  }
    62  
    63  func (c *ValuesContext) Get(key interface{}) (interface{}, bool) {
    64  	return c.Context.Value(defaultCtxKey).(Values).Get(key)
    65  }
    66  
    67  func (c *ValuesContext) Delete(key interface{}) {
    68  	c.Context.Value(defaultCtxKey).(Values).Delete(key)
    69  }
    70  
    71  func (c *ValuesContext) Set(key interface{}, value interface{}) {
    72  	c.Context.Value(defaultCtxKey).(Values).Set(key, value)
    73  }