github.com/blend/go-sdk@v1.20220411.3/web/state.go (about)

     1  /*
     2  
     3  Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file.
     5  
     6  */
     7  
     8  package web
     9  
    10  import "sync"
    11  
    12  // State is a provider for a state bag.
    13  type State interface {
    14  	Keys() []string
    15  	Get(key string) interface{}
    16  	Set(key string, value interface{})
    17  	Remove(key string)
    18  	Copy() State
    19  }
    20  
    21  // SyncState is the collection of state objects on a context.
    22  type SyncState struct {
    23  	sync.RWMutex
    24  	Values map[string]interface{}
    25  }
    26  
    27  // Keys returns
    28  func (s *SyncState) Keys() (output []string) {
    29  	s.Lock()
    30  	defer s.Unlock()
    31  	if s.Values == nil {
    32  		return
    33  	}
    34  
    35  	output = make([]string, len(s.Values))
    36  	var index int
    37  	for key := range s.Values {
    38  		output[index] = key
    39  		index++
    40  	}
    41  	return
    42  }
    43  
    44  // Get gets a value.
    45  func (s *SyncState) Get(key string) interface{} {
    46  	s.RLock()
    47  	defer s.RUnlock()
    48  	if s.Values == nil {
    49  		return nil
    50  	}
    51  	return s.Values[key]
    52  }
    53  
    54  // Set sets a value.
    55  func (s *SyncState) Set(key string, value interface{}) {
    56  	s.Lock()
    57  	defer s.Unlock()
    58  	if s.Values == nil {
    59  		s.Values = make(map[string]interface{})
    60  	}
    61  	s.Values[key] = value
    62  }
    63  
    64  // Remove removes a key.
    65  func (s *SyncState) Remove(key string) {
    66  	s.Lock()
    67  	defer s.Unlock()
    68  	if s.Values == nil {
    69  		return
    70  	}
    71  	delete(s.Values, key)
    72  }
    73  
    74  // Copy creates a new copy of the vars.
    75  func (s *SyncState) Copy() State {
    76  	s.RLock()
    77  	defer s.RUnlock()
    78  	return &SyncState{
    79  		Values: s.Values,
    80  	}
    81  }