github.com/Azareal/Gosora@v0.0.0-20210729070923-553e66b59003/common/widget_store.go (about)

     1  package common
     2  
     3  import (
     4  	"database/sql"
     5  	"sync"
     6  )
     7  
     8  var Widgets *DefaultWidgetStore
     9  
    10  type DefaultWidgetStore struct {
    11  	widgets map[int]*Widget
    12  	sync.RWMutex
    13  }
    14  
    15  func NewDefaultWidgetStore() *DefaultWidgetStore {
    16  	return &DefaultWidgetStore{widgets: make(map[int]*Widget)}
    17  }
    18  
    19  func (s *DefaultWidgetStore) Get(id int) (*Widget, error) {
    20  	s.RLock()
    21  	defer s.RUnlock()
    22  	w, ok := s.widgets[id]
    23  	if !ok {
    24  		return w, sql.ErrNoRows
    25  	}
    26  	return w, nil
    27  }
    28  
    29  func (s *DefaultWidgetStore) set(w *Widget) {
    30  	s.Lock()
    31  	defer s.Unlock()
    32  	s.widgets[w.ID] = w
    33  }
    34  
    35  func (s *DefaultWidgetStore) delete(id int) {
    36  	s.Lock()
    37  	defer s.Unlock()
    38  	delete(s.widgets, id)
    39  }