From e20026614be2e663fd77d7d6eb573f96f44601bf 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 | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/main.go b/main.go index 560b28e..3b55c21 100644 --- a/main.go +++ b/main.go @@ -1,9 +1,9 @@ package main import ( - "bytes" "context" "fmt" + "io/ioutil" "net/http" "net/url" "os" @@ -50,9 +50,18 @@ func (mycli *MyClient) eventHandler(evt interface{}) { 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) @@ -108,7 +117,8 @@ 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