diff --git a/common/client.go b/common/client.go index 14e8625..6040c5c 100644 --- a/common/client.go +++ b/common/client.go @@ -1,7 +1,10 @@ package common import ( + "bytes" "crypto/tls" + "fmt" + "io/ioutil" "net/http" "github.com/greenled/portainer-stack-utils/util" @@ -32,12 +35,47 @@ func GetDefaultClient() (c client.PortainerClient, err error) { } c.BeforeRequest(func(req *http.Request) (err error) { - util.PrintDebugRequest("Request", req) + var bodyString string + if req.Body != nil { + bodyBytes, readErr := ioutil.ReadAll(req.Body) + defer req.Body.Close() + if readErr != nil { + return readErr + } + bodyString = string(bodyBytes) + req.Body = ioutil.NopCloser(bytes.NewReader(bodyBytes)) + } + + util.PrintDebug(fmt.Sprintf(`Request +--- +Method: %s +URL: %s +Body: +%s +---`, req.Method, req.URL.String(), string(bodyString))) + return }) c.AfterResponse(func(resp *http.Response) (err error) { - util.PrintDebugResponse("Response", resp) + var bodyString string + if resp.Body != nil { + bodyBytes, readErr := ioutil.ReadAll(resp.Body) + defer resp.Body.Close() + if readErr != nil { + return readErr + } + bodyString = string(bodyBytes) + resp.Body = ioutil.NopCloser(bytes.NewReader(bodyBytes)) + } + + util.PrintDebug(fmt.Sprintf(`Response +--- +Status: %s +Body: +%s +---`, resp.Status, bodyString)) + return }) diff --git a/util/printing.go b/util/printing.go index 152a1a0..94a1d73 100644 --- a/util/printing.go +++ b/util/printing.go @@ -1,11 +1,8 @@ package util import ( - "bytes" "fmt" - "io/ioutil" "log" - "net/http" "os" "strings" "text/tabwriter" @@ -33,52 +30,3 @@ func NewTabWriter(headers []string) (*tabwriter.Writer, error) { } return writer, nil } - -func PrintDebugRequest(title string, req *http.Request) error { - if viper.GetBool("debug") { - var bodyString string - if req.Body != nil { - bodyBytes, err := ioutil.ReadAll(req.Body) - defer req.Body.Close() - if err != nil { - return err - } - bodyString = string(bodyBytes) - req.Body = ioutil.NopCloser(bytes.NewReader(bodyBytes)) - } - - PrintDebug(fmt.Sprintf(`%s ---- -Method: %s -URL: %s -Body: -%s ----`, title, req.Method, req.URL.String(), string(bodyString))) - } - - return nil -} - -func PrintDebugResponse(title string, resp *http.Response) error { - if viper.GetBool("debug") { - var bodyString string - if resp.Body != nil { - bodyBytes, err := ioutil.ReadAll(resp.Body) - defer resp.Body.Close() - if err != nil { - return err - } - bodyString = string(bodyBytes) - resp.Body = ioutil.NopCloser(bytes.NewReader(bodyBytes)) - } - - PrintDebug(fmt.Sprintf(`%s ---- -Status: %s -Body: -%s ----`, title, resp.Status, bodyString)) - } - - return nil -}