add locker

This commit is contained in:
xinfei.wu 2019-01-09 14:24:12 +08:00 committed by GitHub
parent d5df31eeb8
commit 453ce2fcbe
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,11 +1,13 @@
// Package mock provides a mock registry for testing
package mock
import (
"sync"
"github.com/micro/go-micro/registry"
)
type mockRegistry struct {
sync.RWMutex
Services map[string][]*registry.Service
}
@ -55,11 +57,17 @@ var (
)
func (m *mockRegistry) init() {
m.Lock()
defer m.Unlock()
// add some mock data
m.Services = mockData
}
func (m *mockRegistry) GetService(service string) ([]*registry.Service, error) {
m.Lock()
defer m.Unlock()
s, ok := m.Services[service]
if !ok || len(s) == 0 {
return nil, registry.ErrNotFound
@ -69,6 +77,9 @@ func (m *mockRegistry) GetService(service string) ([]*registry.Service, error) {
}
func (m *mockRegistry) ListServices() ([]*registry.Service, error) {
m.Lock()
defer m.Unlock()
var services []*registry.Service
for _, service := range m.Services {
services = append(services, service...)
@ -77,12 +88,18 @@ func (m *mockRegistry) ListServices() ([]*registry.Service, error) {
}
func (m *mockRegistry) Register(s *registry.Service, opts ...registry.RegisterOption) error {
m.Lock()
defer m.Unlock()
services := addServices(m.Services[s.Name], []*registry.Service{s})
m.Services[s.Name] = services
return nil
}
func (m *mockRegistry) Deregister(s *registry.Service) error {
m.Lock()
defer m.Unlock()
services := delServices(m.Services[s.Name], []*registry.Service{s})
m.Services[s.Name] = services
return nil