From aac76f67912460c63464877010c1cc6d76557116 Mon Sep 17 00:00:00 2001 From: Denozordec Date: Fri, 10 Apr 2026 00:47:10 +0700 Subject: [PATCH] Refactor callTelemtJSON function in main.go to accept multiple success HTTP status codes, enhancing error handling for user creation requests. Introduce httpStatusInList helper function to streamline status code validation. --- main.go | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/main.go b/main.go index 808a008..dec77ec 100644 --- a/main.go +++ b/main.go @@ -465,7 +465,7 @@ func (b *bot) handleCreateUser(ctx context.Context, chatID int64, text string) e req := createUserRequest{Username: username} var created createUserResponse - if err := b.callTelemtJSON(ctx, http.MethodPost, "/v1/users", req, &created, http.StatusCreated); err != nil { + if err := b.callTelemtJSON(ctx, http.MethodPost, "/v1/users", req, &created, http.StatusCreated, http.StatusAccepted); err != nil { return b.sendMessage(ctx, chatID, "Ошибка создания пользователя: "+err.Error()) } @@ -889,7 +889,7 @@ func (b *bot) handleCreateUserDirect(ctx context.Context, chatID int64, username req := createUserRequest{Username: username} var created createUserResponse - if err := b.callTelemtJSON(ctx, http.MethodPost, "/v1/users", req, &created, http.StatusCreated); err != nil { + if err := b.callTelemtJSON(ctx, http.MethodPost, "/v1/users", req, &created, http.StatusCreated, http.StatusAccepted); err != nil { return b.sendMessageWithKeyboard(ctx, chatID, "Ошибка создания пользователя: "+err.Error(), mainMenuKeyboard()) } @@ -939,7 +939,19 @@ func (b *bot) callTelemt(ctx context.Context, path string, out any) error { return b.callTelemtJSON(ctx, http.MethodGet, path, nil, out, http.StatusOK) } -func (b *bot) callTelemtJSON(ctx context.Context, method, path string, payload any, out any, successStatus int) error { +func httpStatusInList(code int, allowed []int) bool { + for _, c := range allowed { + if code == c { + return true + } + } + return false +} + +func (b *bot) callTelemtJSON(ctx context.Context, method, path string, payload any, out any, successStatuses ...int) error { + if len(successStatuses) == 0 { + return errors.New("callTelemtJSON: at least one success HTTP status required") + } cctx, cancel := context.WithTimeout(ctx, b.cfg.TelemtTimeout) defer cancel() @@ -973,13 +985,13 @@ func (b *bot) callTelemtJSON(ctx context.Context, method, path string, payload a var env telemtEnvelope if err := json.NewDecoder(resp.Body).Decode(&env); err != nil { - if resp.StatusCode != successStatus { + if !httpStatusInList(resp.StatusCode, successStatuses) { return fmt.Errorf("telemt status %s", resp.Status) } return fmt.Errorf("telemt decode response: %w", err) } - if resp.StatusCode != successStatus { + if !httpStatusInList(resp.StatusCode, successStatuses) { if env.Error != nil { return fmt.Errorf("%s: %s", env.Error.Code, env.Error.Message) }