Skip to content
This repository has been archived by the owner on Sep 13, 2023. It is now read-only.

Commit

Permalink
Merge pull request #16 from palavrapasse/15-enhancement-non-blocking-…
Browse files Browse the repository at this point in the history
…telegram-api-calls

enhancement: non blocking telegram api calls
  • Loading branch information
rutesantos4 authored Feb 11, 2023
2 parents ef0808f + 1984bd5 commit c1778dc
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
Empty file added go.sum
Empty file.
22 changes: 18 additions & 4 deletions pkg/telegramwriter.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ type TelegramWriter struct {
chatId string
}

var resultChan = make(chan *http.Response)

func (tw TelegramWriter) Write(p []byte) (n int, err error) {

body, err := json.Marshal(map[string]string{
Expand All @@ -25,13 +27,25 @@ func (tw TelegramWriter) Write(p []byte) (n int, err error) {

url := fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", tw.botToken)

go asyncPost(url, body, resultChan)

response := <-resultChan
defer func() {
if response != nil && response.Body != nil {
response.Body.Close()
}
}()

return len(p), nil
}

func asyncPost(url string, body []byte, rc chan *http.Response) {
response, err := http.Post(url, messageType, bytes.NewBuffer(body))

if err != nil {
return 0, err
rc <- response
return
}

defer response.Body.Close()

return len(p), nil
rc <- response
}

0 comments on commit c1778dc

Please sign in to comment.