diff options
| author | Paul Buetow <paul@buetow.org> | 2023-06-19 21:54:09 +0300 |
|---|---|---|
| committer | Paul Buetow <paul@buetow.org> | 2023-06-19 21:54:09 +0300 |
| commit | af2d61921f76cfc0696d4a8caf457fc91ae472d8 (patch) | |
| tree | 05a7fa24bd82972465a7d77d6542f703c1b29cde /internal/config | |
| parent | dbf23cb423b15fd94930b042f402dfa8d8a76a17 (diff) | |
get node number correct
Diffstat (limited to 'internal/config')
| -rw-r--r-- | internal/config/config.go | 29 | ||||
| -rw-r--r-- | internal/config/config_test.go | 15 |
2 files changed, 22 insertions, 22 deletions
diff --git a/internal/config/config.go b/internal/config/config.go index e5cd224..dcec535 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -12,12 +12,13 @@ import ( ) type Config struct { - StateDir string - Address string - Nodes []string - LoopIntervalS int64 `json:"LoopIntervalS,omitempty"` - MyID string `json:"MyID,omitempty"` - RelaxedMode bool `json:"RelaxedMode,omitempty"` + StateDir string + Address string + Nodes []string + LoopIntervalS int64 `json:"LoopIntervalS,omitempty"` + MyID string `json:"MyID,omitempty"` + RelaxedMode bool `json:"RelaxedMode,omitempty"` + nodeNumberCache map[string]int } func New(configFile string) (Config, error) { @@ -54,14 +55,24 @@ func New(configFile string) (Config, error) { return c, nil } -func (c Config) NodeNumber(node string) (int, error) { +func (c *Config) NodeNumber(node string) int { + if c.nodeNumberCache == nil { + c.nodeNumberCache = make(map[string]int, len(c.Nodes)) + } + nodeNumber, ok := c.nodeNumberCache[node] + if ok { + return nodeNumber + } + for i, node_ := range c.Nodes { if node == utils.StripPort(node_) { - return i, nil + c.nodeNumberCache[node] = i + return i } } - return 0, fmt.Errorf("node %s not found", node) + log.Println("config:", fmt.Errorf("node %s not found - it will affect it's score!", node)) + return 0 } func (c Config) IsNode(remoteAddr string) bool { diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 2fcfefb..7927664 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -10,26 +10,15 @@ func TestNodeNumber(t *testing.T) { t.Parallel() conf := Config{Nodes: []string{"localhost:1234", "hamburger:4321"}} - num, err := conf.NodeNumber("localhost") - if err != nil { - t.Errorf(err.Error()) - } + num := conf.NodeNumber("localhost") if num != 0 { t.Errorf("localhost should be node number 0 but is %d", num) } - num, err = conf.NodeNumber("hamburger") - if err != nil { - t.Errorf(err.Error()) - } + num = conf.NodeNumber("hamburger") if num != 1 { t.Errorf("hamburger should be node number 1 but is %d", num) } - - _, err = conf.NodeNumber("doener") - if err == nil { - t.Errorf("doener is not a node") - } } func TestIsNode(t *testing.T) { |
