From 44b43be9f0ba79527861448186e4dfae4d3c22ae Mon Sep 17 00:00:00 2001 From: Emmanuel T Odeke Date: Sun, 4 Dec 2022 20:27:46 -0800 Subject: [PATCH] go/clientConnector: fix signal handling, non-2XX HTTP responses, redundant 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 --- main.go | 23 +++++++++++++++++------ 1 file changed, 17 insertions(+), 6 deletions(-) diff --git a/main.go b/main.go index 560b28e..3d77659 100644 --- a/main.go +++ b/main.go @@ -1,9 +1,9 @@ package main import ( - "bytes" "context" "fmt" + "io/ioutil" "net/http" "net/url" "os" @@ -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) @@ -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() @@ -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() }