Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

go/clientConnector: fix signal handling, non-2XX HTTP responses, redundant body reading #16

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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()

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should be deferred... no?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No need to, this code closes it immediately after use. A defer will keep it open until the function returns or panics and then that's when the close will happen.

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