2022-04-28 16:35:02 +00:00
|
|
|
package config
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"strings"
|
|
|
|
"sync"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
ErrServerNameAlreadyRegistered = errors.New("server name is already registered")
|
|
|
|
ErrNoSuchServer = errors.New("no known server with given name")
|
2022-05-08 09:00:22 +00:00
|
|
|
|
|
|
|
_ ServerLookup = (*ServerRegister)(nil)
|
|
|
|
)
|
|
|
|
|
|
|
|
type ServerLookup interface {
|
|
|
|
Lookup(name string) (*Server, error)
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewServerRegister() *ServerRegister {
|
|
|
|
return &ServerRegister{
|
2022-04-28 16:35:02 +00:00
|
|
|
servers: make(map[string]Server),
|
|
|
|
}
|
2022-05-08 09:00:22 +00:00
|
|
|
}
|
2022-04-28 16:35:02 +00:00
|
|
|
|
2022-05-08 09:00:22 +00:00
|
|
|
type ServerRegister struct {
|
2022-04-28 16:35:02 +00:00
|
|
|
lock sync.RWMutex
|
|
|
|
servers map[string]Server
|
|
|
|
}
|
|
|
|
|
2022-05-08 09:00:22 +00:00
|
|
|
func (l *ServerRegister) Register(name string, srv Server) error {
|
2022-04-28 16:35:02 +00:00
|
|
|
l.lock.Lock()
|
|
|
|
defer l.lock.Unlock()
|
|
|
|
|
|
|
|
name = strings.ToLower(name)
|
|
|
|
|
|
|
|
if _, ok := l.servers[name]; ok {
|
|
|
|
return fmt.Errorf("%w: %s", ErrServerNameAlreadyRegistered, name)
|
|
|
|
}
|
|
|
|
|
|
|
|
l.servers[name] = srv
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-05-08 09:00:22 +00:00
|
|
|
func (l *ServerRegister) Lookup(name string) (*Server, error) {
|
2022-04-28 16:35:02 +00:00
|
|
|
l.lock.RLock()
|
|
|
|
defer l.lock.RUnlock()
|
|
|
|
|
|
|
|
name = strings.ToLower(name)
|
|
|
|
|
|
|
|
match, ok := l.servers[name]
|
|
|
|
if !ok {
|
|
|
|
return nil, fmt.Errorf("%w: %s", ErrNoSuchServer, name)
|
|
|
|
}
|
|
|
|
return &match, nil
|
|
|
|
}
|