Skip to content

Commit

Permalink
chore: fix HTTP dump hooks
Browse files Browse the repository at this point in the history
  • Loading branch information
pmalek committed Oct 14, 2024
1 parent 2361947 commit 2238daa
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 11 deletions.
34 changes: 25 additions & 9 deletions internal/hooks/httpdump.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ func (i *HTTPDumpRequestHook) BeforeRequest(hookCtx BeforeRequestContext, req *h
if !i.Enabled {
return req, nil
}
if req == nil {
return nil, nil
}

b, err := httputil.DumpRequestOut(req, true)
if err != nil {
Expand All @@ -38,21 +41,34 @@ var _ afterSuccessHook = (*HTTPDumpResponseHook)(nil)

// AfterSuccess dumps the response to stdout if enabled.
func (i *HTTPDumpResponseHook) AfterSuccess(hookCtx AfterSuccessContext, res *http.Response) (*http.Response, error) {
return i.dumpResponse(res)
if !i.Enabled {
return res, nil
}
return dumpResponse(res), nil
}

var _ afterErrorHook = (*HTTPDumpResponseHook)(nil)

// AfterSuccess dumps the response to stdout if enabled.
func (i *HTTPDumpResponseHook) AfterError(hookCtx AfterErrorContext, res *http.Response, err error) (*http.Response, error) {
fmt.Printf("Error: %v\n", err)
return i.dumpResponse(res)
// HTTPDumpResponseErrorHook is a hook that dumps the error response to stdout.
type HTTPDumpResponseErrorHook struct {
Enabled bool
}

func (i *HTTPDumpResponseHook) dumpResponse(res *http.Response) (*http.Response, error) {
var _ afterErrorHook = (*HTTPDumpResponseErrorHook)(nil)

// AfterError dumps the error response to stdout if enabled.
func (i *HTTPDumpResponseErrorHook) AfterError(hookCtx AfterErrorContext, res *http.Response, err error) (*http.Response, error) {
if !i.Enabled {
return res, nil
}
if err != nil {
fmt.Printf("Error: %v\n", err)
}
return dumpResponse(res), err
}

func dumpResponse(res *http.Response) *http.Response {
if res == nil {
return nil
}

b, err := httputil.DumpResponse(res, true)
if err != nil {
Expand All @@ -61,5 +77,5 @@ func (i *HTTPDumpResponseHook) dumpResponse(res *http.Response) (*http.Response,
fmt.Printf("response:\n%s\n\n", b)
}

return res, nil
return res
}
4 changes: 2 additions & 2 deletions internal/hooks/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ func initHooks(h *Hooks) {
h.registerAfterSuccessHook(&HTTPDumpResponseHook{
Enabled: os.Getenv("KONNECT_SDK_HTTP_DUMP_RESPONSE") == "true",
})
h.registerAfterErrorHook(&HTTPDumpResponseHook{
Enabled: os.Getenv("KONNECT_SDK_HTTP_DUMP_RESPONSE") == "true",
h.registerAfterErrorHook(&HTTPDumpResponseErrorHook{
Enabled: os.Getenv("KONNECT_SDK_HTTP_DUMP_RESPONSE_ERROR") == "true",
})
}

0 comments on commit 2238daa

Please sign in to comment.