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.
Publish telemt-bot Docker image / build-and-push (push) Successful in 57s

This commit is contained in:
Denozordec
2026-04-10 00:47:10 +07:00
parent 6243163232
commit aac76f6791
+17 -5
View File
@@ -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)
}