github.com/XiaoMi/Gaea@v1.2.5/util/request_context.go (about)

     1  // Copyright 2019 The Gaea Authors. All Rights Reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package util
    16  
    17  import (
    18  	"sync"
    19  )
    20  
    21  const (
    22  	// StmtType stmt type
    23  	StmtType = "stmtType" // SQL类型, 值类型为int (对应parser.Preview()得到的值)
    24  	// FromSlave if read from slave
    25  	FromSlave    = "fromSlave"    // 读写分离标识, 值类型为int, false = 0, true = 1
    26  	DefaultSlice = "defaultSlice" // 默认分片标识 string 类型
    27  )
    28  
    29  // RequestContext means request scope context with values
    30  // thread safe
    31  type RequestContext struct {
    32  	lock *sync.RWMutex
    33  	ctx  map[string]interface{}
    34  }
    35  
    36  // NewRequestContext return request scopre context
    37  func NewRequestContext() *RequestContext {
    38  	return &RequestContext{ctx: make(map[string]interface{}, 2), lock: new(sync.RWMutex)}
    39  }
    40  
    41  // Get return context in RequestContext
    42  func (reqCtx *RequestContext) Get(key string) interface{} {
    43  	reqCtx.lock.RLock()
    44  	v, ok := reqCtx.ctx[key]
    45  	reqCtx.lock.RUnlock()
    46  	if ok {
    47  		return v
    48  	}
    49  	return nil
    50  }
    51  
    52  // Set set value with specific key
    53  func (reqCtx *RequestContext) Set(key string, value interface{}) {
    54  	reqCtx.lock.Lock()
    55  	reqCtx.ctx[key] = value
    56  	reqCtx.lock.Unlock()
    57  }