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 <[email protected]>
  • Loading branch information
odeke-em committed Dec 5, 2022
1 parent d126932 commit e200266
Showing 1 changed file with 15 additions and 5 deletions.
20 changes: 15 additions & 5 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 @@ -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)
Expand Down Expand Up @@ -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

Expand Down

0 comments on commit e200266

Please sign in to comment.