github.com/gramework/gramework@v1.8.1-0.20231027140105-82555c9057f5/infrastructure/infrastructure_RegisterService.go (about)

     1  package infrastructure
     2  
     3  import (
     4  	"errors"
     5  )
     6  
     7  var (
     8  	// ErrServiceExists occurs when you trying to register a service that already exists
     9  	ErrServiceExists = errors.New("service exists")
    10  )
    11  
    12  // RegisterService in the infrastructure
    13  func (i *Infrastructure) RegisterService(name string, s Service) error {
    14  	i.Lock.RLock()
    15  	if _, ok := i.Services[name]; ok {
    16  		i.Lock.RUnlock()
    17  		return ErrServiceExists
    18  	}
    19  	i.Lock.RUnlock()
    20  	i.Lock.Lock()
    21  	if s.Name == "" {
    22  		s.Name = name
    23  	}
    24  	i.Services[name] = &s
    25  	i.Lock.Unlock()
    26  
    27  	return nil
    28  }
    29  
    30  // RegisterServiceBatch registers services from given map[service name]Service
    31  // Returns error if service already exists
    32  func (i *Infrastructure) RegisterServiceBatch(m map[string]Service) error {
    33  	for name, s := range m {
    34  		err := i.RegisterService(name, s)
    35  		if err != nil {
    36  			return err
    37  		}
    38  	}
    39  
    40  	return nil
    41  }
    42  
    43  // RegisterServiceBatchIgnore registers services from given map[service name]Service
    44  // Ignores any error if service already exists
    45  func (i *Infrastructure) RegisterServiceBatchIgnore(m map[string]Service) {
    46  	for name, s := range m {
    47  		e := i.RegisterService(name, s)
    48  		_ = e
    49  	}
    50  }
    51  
    52  // MergeService in the infrastructure
    53  func (i *Infrastructure) MergeService(name string, s Service) {
    54  	i.Lock.Lock()
    55  	if _, ok := i.Services[name]; ok {
    56  		i.Services[name].Addresses = append(i.Services[name].Addresses, s.Addresses...)
    57  		i.Lock.Unlock()
    58  		return
    59  	}
    60  	i.Services[name] = &s
    61  	i.Lock.Unlock()
    62  }