Skip to content

Commit

Permalink
go/clientConnector: fix signal handling, non-2XX HTTP responses, redu…
Browse files Browse the repository at this point in the history
…ndant body reading

This change adds proper signal handling by passing in a buffered
signal channel to signal.Notify as it mandates at https://pkg.go.dev/os/signal#Notify
It also handles non-2XX codes and reports this while printing the
content and returning.
While here also added resp.Body.Close() to avoid leaking HTTP responses.
Also removes redundant bytes.Buffer.ReadFrom, then .String() and string(newMsg)
by simply using io/ioutil.ReadAll(resp.Body) given we aren't sure which
version of Go being used but really in >=Go1.16, we can use io.ReadAll

Fixes #13
Fixes #14
Fixes #15

Signed-off-by: Emmanuel T Odeke <emmanuel@orijtech.com>
  • Loading branch information
odeke-em committed Dec 5, 2022
1 parent d126932 commit 44b43be
Showing 1 changed file with 17 additions and 6 deletions.
23 changes: 17 additions & 6 deletions main.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
package main

import (
"bytes"
"context"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"os"
Expand Down Expand Up @@ -49,10 +49,20 @@ func (mycli *MyClient) eventHandler(evt interface{}) {
fmt.Println("Error making request:", err)
return
}

// Read the response
buf := new(bytes.Buffer)
buf.ReadFrom(resp.Body)
newMsg := buf.String()
newMsg, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
fmt.Printf("Error reading response: %v\n", err)
return
}

if resp.StatusCode/100 != 2 { // If we don't encounter a 2XX status code, fail.
fmt.Printf("Non-2XX response: %s\nResponse body: %s\n", resp.Status, newMsg)
return
}

// encode out as a string
response := &waProto.Message{Conversation: proto.String(string(newMsg))}
fmt.Println("Response:", response)
Expand All @@ -77,6 +87,7 @@ func main() {
}
clientLog := waLog.Stdout("Client", "DEBUG", true)
client := whatsmeow.NewClient(deviceStore, clientLog)

// add the eventHandler
mycli := &MyClient{WAClient: client}
mycli.register()
Expand Down Expand Up @@ -108,9 +119,9 @@ func main() {
}

// Listen to Ctrl+C (you can also do something else that prevents the program from exiting)
c := make(chan os.Signal)
// Notify requires that there be enough capachttps://pkg.go.dev/os/signal#Notify
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
<-c

client.Disconnect()
}

0 comments on commit 44b43be

Please sign in to comment.