Skip to content

Commit

Permalink
refactor: remove multiple print statements
Browse files Browse the repository at this point in the history
Signed-off-by: 1998-felix <felix.gateru@gmail.com>
  • Loading branch information
felixgateru committed May 15, 2024
1 parent ab88344 commit 1fc0152
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 14 deletions.
18 changes: 13 additions & 5 deletions cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,13 @@ var (
maxRetries uint32
)

const verboseFmt = `Date: %s
Code: %s
Type: %s
Token: %s
Message-ID: %d
`

func main() {
rootCmd := &cobra.Command{
Use: "coap-cli <method> <URL> [options]",
Expand Down Expand Up @@ -95,11 +102,12 @@ func main() {

func printMsg(m *pool.Message, verbose bool) {
if m != nil && verbose {
fmt.Printf("Date: %s\n", time.Now().Format(time.RFC1123))
fmt.Printf("Code: %s\n", m.Code().String())
fmt.Printf("Type: %s\n", m.Type().String())
fmt.Printf("Token: %s\n", m.Token().String())
fmt.Printf("Message-ID: %d\n", m.MessageID())
fmt.Printf(verboseFmt,
time.Now().Format(time.RFC1123),
m.Code(),
m.Type(),
m.Token(),
m.MessageID())
cf, err := m.ContentFormat()
if err == nil {
fmt.Printf("Content-Format: %s \n", cf.String())
Expand Down
27 changes: 18 additions & 9 deletions coap/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,17 @@ import (

var (
errInvalidMsgCode = errors.New("message can be GET, POST, PUT or DELETE")
errDialFailed = errors.New("Failed to dial the connection")
errDialFailed = errors.New("failed to dial the connection")
)

const verboseFmt = `Date: %s
Code: %s
Type: %s
Token: %s
Message-ID: %d
Content-Length: %d
`

// Client represents CoAP client.
type Client struct {
conn *client.Conn
Expand Down Expand Up @@ -73,22 +81,23 @@ func (c Client) Receive(path string, verbose bool, opts ...message.Option) (mux.
fmt.Println("Error reading message body: ", err)
return
}
bs, err := res.BodySize()
bodySize, err := res.BodySize()
if err != nil {
fmt.Println("Error getting body size: ", err)
return
}
if bs == 0 {
if bodySize == 0 {
fmt.Println("Received observe")
}
switch verbose {
case true:
fmt.Printf("Date: %s\n", time.Now().Format(time.RFC1123))
fmt.Printf("Code: %s\n", res.Code().String())
fmt.Printf("Type: %s\n", res.Type().String())
fmt.Printf("Token: %s\n", res.Token().String())
fmt.Printf("Message-ID: %d\n", res.MessageID())
fmt.Printf("Content-Length: %d\n", bs)
fmt.Printf(verboseFmt,
time.Now().Format(time.RFC1123),
res.Code(),
res.Type(),
res.Token(),
res.MessageID(),
bodySize)
if len(body) > 0 {
fmt.Printf("Payload: %s\n\n", string(body))
}
Expand Down

0 comments on commit 1fc0152

Please sign in to comment.