Skip to content

Commit

Permalink
Add: context value
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexStocks committed Jan 11, 2020
1 parent 9f51439 commit da528eb
Show file tree
Hide file tree
Showing 2 changed files with 98 additions and 0 deletions.
73 changes: 73 additions & 0 deletions context/context.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/*
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package gxcontext

import (
"context"
)

var (
defaultCtxKey = 1
)

type Values struct {
m map[interface{}]interface{}
}

func (v Values) Get(key interface{}) (interface{}, bool) {
i, b := v.m[key]
return i, b
}

func (c Values) Set(key interface{}, value interface{}) {
c.m[key] = value
}

func (c Values) Delete(key interface{}) {
delete(c.m, key)
}

type ValuesContext struct {
context.Context
}

func NewValuesContext(ctx context.Context) *ValuesContext {
if ctx == nil {
ctx = context.Background()
}

return &ValuesContext{
Context: context.WithValue(
ctx,
defaultCtxKey,
Values{m: make(map[interface{}]interface{}, 4)},
),
}
}

func (c *ValuesContext) Get(key interface{}) (interface{}, bool) {
return c.Context.Value(defaultCtxKey).(Values).Get(key)
}

func (c *ValuesContext) Delete(key interface{}) {
c.Context.Value(defaultCtxKey).(Values).Delete(key)
}

func (c *ValuesContext) Set(key interface{}, value interface{}) {
c.Context.Value(defaultCtxKey).(Values).Set(key, value)
}
25 changes: 25 additions & 0 deletions context/context_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package gxcontext

import (
"testing"
)

import (
"github.com/stretchr/testify/assert"
)

func TestValuesContext_General(t *testing.T) {
vc := NewValuesContext(nil)
assert.NotNil(t, vc)

key := "hello"
value := "world"
v, ok := vc.Get(key)
assert.Nil(t, v)
assert.False(t, ok)

vc.Set(key, value)
v, ok = vc.Get(key)
assert.Equal(t, v.(string), value)
assert.True(t, ok)
}

0 comments on commit da528eb

Please sign in to comment.