From 190cc93b3e446ef232f1fddb85c65f6b402a8c89 Mon Sep 17 00:00:00 2001 From: Behrad Ravanbod <99behi@gmail.com> Date: Sat, 29 Jun 2024 11:12:33 +0330 Subject: [PATCH] Fix mattermost json problem, fix returning error in mattermost and telegram --- internal/repository/notification/mattermost.go | 18 +++++++++++++----- internal/repository/notification/telegram.go | 2 +- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/internal/repository/notification/mattermost.go b/internal/repository/notification/mattermost.go index 3886fbe..cc25c6d 100644 --- a/internal/repository/notification/mattermost.go +++ b/internal/repository/notification/mattermost.go @@ -2,8 +2,9 @@ package notification import ( "bytes" + "encoding/json" "errors" - "fmt" + "io" "net/http" "strconv" "time" @@ -21,17 +22,24 @@ func NewMattermostNotificationSender(host string, bearerAuth string, channelId s func (r mattermostNotificationSender) SendMessage(message string) error { url := r.host + "/api/v4/posts" - jsonData := fmt.Sprintf("{\"message\":%s, \"channel_id\":\"%s\"}", message, r.channelId) + m := make(map[string]interface{}) // I could not use normal fmt.Sprintf, because the message is multiline and mattermost returns error + m["message"] = message + m["channel_id"] = r.channelId + jsonData, err := json.Marshal(m) + if err != nil { + return err + } client := &http.Client{Timeout: time.Second * 5} - req, _ := http.NewRequest("POST", url, bytes.NewBuffer([]byte(jsonData))) + req, _ := http.NewRequest("POST", url, bytes.NewBuffer(jsonData)) req.Header.Set("Authorization", "Bearer "+r.bearerAuth) res, err := client.Do(req) if err != nil { return err } if res.StatusCode >= 400 { - err = errors.New("Status code is more than 399 error=" + strconv.Itoa(res.StatusCode)) + body, _ := io.ReadAll(res.Body) + err = errors.New("Status code is more than 399 error=" + strconv.Itoa(res.StatusCode) + " body=" + string(body)) } - return nil + return err } diff --git a/internal/repository/notification/telegram.go b/internal/repository/notification/telegram.go index 8a481e8..ddf7e8e 100644 --- a/internal/repository/notification/telegram.go +++ b/internal/repository/notification/telegram.go @@ -32,5 +32,5 @@ func (r telegramNotificationSender) SendMessage(message string) error { if res.StatusCode >= 400 { err = errors.New("Status code is more than 399 error=" + strconv.Itoa(res.StatusCode)) } - return nil + return err }