Skip to content

Commit

Permalink
feat: enable HTTP request/response logging in debug mode (#50)
Browse files Browse the repository at this point in the history
- Add `debug` field to `Client` struct
- Initialize `httpClient` with `debugTransport` if `debug` mode is enabled
- Create `debug.go` to define `debugTransport` for logging HTTP requests and responses
- Add `WithDebug` option to configure debug mode in `option.go`

Signed-off-by: appleboy <[email protected]>
  • Loading branch information
appleboy authored May 25, 2024
1 parent 83a5230 commit 8cbe79b
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 0 deletions.
15 changes: 15 additions & 0 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ type Client struct {
options []option.ClientOption
httpClient *http.Client
credentialsJSON []byte // credentialsJSON is the JSON representation of the service account credentials.
debug bool
}

// NewClient creates new Firebase Cloud Messaging Client based on API key and
Expand All @@ -57,6 +58,20 @@ func NewClient(ctx context.Context, opts ...Option) (*Client, error) {
}
}

if c.debug {
if c.httpClient == nil {
c.httpClient = &http.Client{
Transport: debugTransport{
t: http.DefaultTransport,
},
}
} else {
c.httpClient.Transport = debugTransport{
t: c.httpClient.Transport,
}
}
}

if c.httpClient != nil {
ctxWithClient := context.WithValue(ctx, oauth2.HTTPClient, c.httpClient)
creds, err := google.CredentialsFromJSON(ctxWithClient, c.credentialsJSON, scopes...)
Expand Down
32 changes: 32 additions & 0 deletions debug.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package fcm

import (
"log"
"net/http"
"net/http/httputil"
)

type debugTransport struct {
t http.RoundTripper
}

func (d debugTransport) RoundTrip(req *http.Request) (*http.Response, error) {
reqDump, err := httputil.DumpRequest(req, true)
if err != nil {
return nil, err
}
log.Printf("%s", reqDump)

resp, err := d.t.RoundTrip(req)
if err != nil {
return nil, err
}

respDump, err := httputil.DumpResponse(resp, true)
if err != nil {
resp.Body.Close()
return nil, err
}
log.Printf("%s", respDump)
return resp, nil
}
8 changes: 8 additions & 0 deletions option.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,3 +94,11 @@ func WithTokenSource(s oauth2.TokenSource) Option {
return nil
}
}

// WithDebug returns Option to configure debug mode.
func WithDebug(debug bool) Option {
return func(c *Client) error {
c.debug = debug
return nil
}
}

0 comments on commit 8cbe79b

Please sign in to comment.