Skip to content

Commit ff16850

Browse files
Andrew Lengtennisleng
authored andcommitted
fix: cache chat_id after reading from file
Hey, good catch on the review! I added caching for the chat_id so we don't read the file every single time. Now it checks if we've already got the value cached and only reads from disk if we haven't seen it before. - Added getChatID() method that returns cached value first - Cache the chat_id in n.conf.ChatID after reading it from file - Changed Notify() to call getChatID() instead of accessing ChatID directly Signed-off-by: Andrew Leng <tennisleng@users.noreply.github.com>
1 parent 13845e5 commit ff16850

File tree

1 file changed

+11
-3
lines changed

1 file changed

+11
-3
lines changed

notify/telegram/telegram.go

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -138,17 +138,25 @@ func (n *Notifier) getBotToken() (string, error) {
138138
}
139139

140140
func (n *Notifier) getChatID() (int64, error) {
141+
// Return cached value if already set
142+
if n.conf.ChatID != 0 {
143+
return n.conf.ChatID, nil
144+
}
145+
146+
// Read from file if ChatIDFile is configured
141147
if len(n.conf.ChatIDFile) > 0 {
142148
content, err := os.ReadFile(n.conf.ChatIDFile)
143149
if err != nil {
144150
return 0, fmt.Errorf("could not read %s: %w", n.conf.ChatIDFile, err)
145151
}
146-
chatIDStr := strings.TrimSpace(string(content))
147-
chatID, err := strconv.ParseInt(chatIDStr, 10, 64)
152+
chatID, err := strconv.ParseInt(strings.TrimSpace(string(content)), 10, 64)
148153
if err != nil {
149154
return 0, fmt.Errorf("could not parse chat_id from %s: %w", n.conf.ChatIDFile, err)
150155
}
156+
// Cache the value for future use
157+
n.conf.ChatID = chatID
151158
return chatID, nil
152159
}
153-
return n.conf.ChatID, nil
160+
161+
return 0, fmt.Errorf("chat_id not configured")
154162
}

0 commit comments

Comments
 (0)